<?php
class api {
	private static $instance; //实例对象
	private $Mcartlist;	//购物车
	private $Mcartlist_team; //组团购物车
	private $go_team_cartlist;	//参团购物车
	private $field; //商品字段
	private $zfield; //直购商品字段
	private $model;
	private $uid; //用户id
	private $userinfo; //用户信息
	private $insert_id; //最后写入ID
	private $jsonp = 'JSONP';
	private $json = 'JSON';
	//对象被防止克隆
	private function __clone(){}
	
	//私有构造
	private function __construct() {
		$this->model = new CoreModel();
	}
	
	//创建单例 实例化
	public static function getInstance(){
		if (!(self::$instance instanceof self)){
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	//初始化api
	public function init(){
		if (isset($_GET['act']) && !empty($_GET['act'])){
			$action = strtolower(_htmtocode($_GET['act']));
			if (!method_exists($this, $action)){
				$this->error();
			}else{
				$this->field = "id,sid,type,cateid,brandid,title,title_style,money,yunjiage,zongrenshu,canyurenshu,shenyurenshu,thumb,qishu,maxqishu,xsjx_time,pos,renqi,time,q_uid,q_user,q_user_code,q_end_time,q_showtime,renqipos,isFree";
				$this->zfield = "id,cateid,brandid,title,title2,keywords,money,oldmoney,yunjiage,zongrenshu,freight,thumb,picarr,time";
				//查询购物车的信息
				$Mcartlist=_getcookie("Cartlist");
				$this->Mcartlist=json_decode(stripslashes($Mcartlist),true);
				
				$Mcartlist_team =_getcookie("team_cartlist");
				$this->Mcartlist_team = json_decode(stripslashes($Mcartlist_team),true);
				
				$go_team_cartlist = _getcookie('go_team_cartlist');
				$this->go_team_cartlist = json_decode(stripslashes($go_team_cartlist),true);
				$this->$action();
			}
		}else{
			$this->error();
		}
	}
	
	//获取用户信息
	private function getUserinfo($type="json"){
		if (!isset($_GET['uid'])) $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'),$type);
		$uid = intval(_encrypt($_GET['uid'],'DECODE'));
		if (!$uid) $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'),$type);
		$userinfo = M('Member')->where(array('uid' => $uid))->find();
		if (empty($userinfo)) $this->ajaxReturn(array('status' => 0,'msg' => '用户不存在'),$type);
		$this->uid = $userinfo['uid'];
		$userinfo['face'] = $userinfo['img'];
		@list($a,$b,$c) = explode('/', $userinfo['img']);
		if (isset($c)){
			$prefix = substr($c, 0,6);
			if ($prefix == 'thumb_'){
				$userinfo['thumb'] = $a.'/'.$b.'/thumb_'.$c;
			}else{
				$userinfo['thumb'] = $userinfo['img'];
			}
		}else{
			$userinfo['thumb'] = $userinfo['img'];
		}
		$userinfo['type_agent'] = 'no';
		if($userinfo['type'] && $userinfo['is_check'] == 2){
			$userinfo['level_name'] = M('agent_level')->where(array('id' => $userinfo['level_id']))->getField('name');
			$userinfo['type_agent'] = 'yes';
		}
		
		$memberdj=$this->excq("select * from `@#_member_group`",2);
		$jingyan=$userinfo['jingyan'];
		if(!empty($memberdj)){
			$x = count($memberdj);
			$userinfo['yungoudj']=$memberdj[$x-1]['name'];
			$userinfo['yungoudj_id'] = $memberdj[$x-1]['groupid'];
			foreach($memberdj as $key=>$val){
				if($jingyan>=$val['jingyan_start'] && $jingyan<=$val['jingyan_end']){
					$userinfo['yungoudj']=$val['name'];
					$userinfo['yungoudj_id'] = $val['groupid'];
				}
			}
		}else{
			$userinfo['yungoudj']='抢购新兵';
			$userinfo['yungoudj_id'] = 1;
		}
		if ($jingyan<=20){
			$userinfo['yungoudj']='抢购新兵';
			$userinfo['yungoudj_id'] = 1;
		}
		$this->userinfo = $userinfo;
	}
	
	private function issue(){
		$field = array('id','cateid','title','posttime');
		$data = M('article')->field($field)->where("area!=1 and cateid!=126")->order('posttime desc')->select();
		$this->ajaxReturn($data);
	}
	
	private function noticelist(){
		$field = array('id','cateid','title','posttime');
		$data = M('article')->field($field)->where("area!=1 and cateid=126")->order('posttime desc')->select();
		$this->ajaxReturn($data);
	}
	
	private function article(){
		$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
		if (!$id) $this->ajaxReturn(array('status' => 0));
		$data = M('article')->where(array('id' => $id))->find();
		$this->ajaxReturn(array('status' => 1,'data' => $data));
	}
	
	//分销中心
	private function fxcenter(){
		$this->getUserinfo($this->jsonp);
		$member=$this->userinfo;
		$uid=$this->userinfo['uid'];
		$notinvolvednum=0;  //未参加购买的人数
		$involvednum=0;     //参加预购的人数
		$involvedtotal=0;   //邀请人数
		//查询邀请好友信息
		$invifriends=$this->excq("select * from `@#_member` where `yaoqing`='$member[uid]' ORDER BY `time` DESC",2);
		$involvedtotal=count($invifriends);
		//var_dump($invifriends);
		for($i=0;$i<count($invifriends);$i++){
			$sqluid=$invifriends[$i]['uid'];
			$sqname=get_user_name($invifriends[$i]);
			$invifriends[$i]['sqlname']=$sqname;
			//查询邀请好友的消费明细
			$accounts[$sqluid]=$this->excq("select * from `@#_member_account` where `uid`='$sqluid'  ORDER BY `time` DESC",2);
			//判断哪个好友有消费
			if(empty($accounts[$sqluid])){
				$notinvolvednum +=1;
				$records[$sqluid]='未参与购买';
			}else{
				$involvednum +=1;
				$records[$sqluid]='已参与购买';
			}
		}
		$userinfo = $this->excq("SELECT uid,yaoqing from `@#_member`",2);
		$fansinfo = $this->getMenuTree($userinfo,$member['uid'],3);
		$allcount = count($fansinfo); //所有粉丝
		$oneLevel=$this->getlevelcount($fansinfo,1); //一级粉丝数量
		$twoLevel = $this->getlevelcount($fansinfo,2); //二级粉丝数量
		$threeLevel = $this->getlevelcount($fansinfo,3); //三级粉丝数量
		$PriceInfo  = $this->getPriceICount($fansinfo,$member['uid']); //返回一个总佣金 和一个已完成的佣金  即单人夺宝的佣金
		$applyMoney = $this->checkApply();//已提现佣金等于 总佣金减去-申请中佣金减去-到账佣金
		$share_price =$member['share_price'];
		$this->ajaxReturn(array(
			'status' => 1,
			'userinfo' => $userinfo,
			'fansinfo' => $fansinfo,
			'allcount' => $allcount,
			'oneLevel' => $oneLevel,
			'twoLevel' => $twoLevel,
			'threeLevel' => $threeLevel,
			'priceInfo' => $PriceInfo,
			'applyMoney' => $applyMoney,
			'sharePrice' => $share_price
		));
	}
	
	/**
	 * @param $arrCat    //所有用户的数据
	 * @param int $parent_id //上级用户的编号
	 * @param int $level //返回用户相应的级别   默认1级不用设置
	 * @param int $agentLevel //设置返回几级的关系 0为不限制级别
	 * @return array|bool
	 */
	
	private  function getMenuTree($arrCat,$parent_id = 0,$agentLevel = 0,$level = 0){
		static  $arrTree = array(); //使用static代替global
		if( empty($arrCat)){ return FALSE;}
		$level++;
		foreach($arrCat as $key => $value){
			//if($value['partnerId'] == $parent_id)
			if($value['yaoqing'] == $parent_id){
				$value['level'] = $level;
				$arrTree[] = $value;
				unset($arrCat[$key]); //注销当前节点数据，减少已无用的遍历
				if($level<$agentLevel || $agentLevel==0){
					self::getMenuTree($arrCat,$value['uid'],$agentLevel,$level);
				}
			}
		}
	
		return $arrTree;
	}

	private function shareapply(){
		$this->getUserinfo();
		$data = $_POST;
		$time=time();
		$userinfo=$this->userinfo;
		$price = $data['price'];
		$pay_bankName = $data['bankName'];
		$pay_trueName = $data['truename'];
		$pay_cardNum = $data['cardId'];
		$pay_bankAccess = $data['cardAccess'];
		$pay_type = 0;
		$uid=$userinfo['uid'];
		$username = $userinfo['username'];
		$price=$data['price'];
		$applyPrice  = $this->checkApply();
		$arr=$this->excq("SELECT * from `@#_share_apply` where `uid`='$uid' and (`status`='0' OR `status`='1') order by time desc");
		if($arr===false &&($applyPrice==$price)>0){
			$res = $this->aud("insert into `@#_share_apply` (`uid`,`username`,`price`,`pay_type`,`pay_bankName`,`pay_trueName`,`pay_cardNum`,`pay_bankAccess`,`status`,`time`) values ('{$uid}','$username','$price','$pay_type','$pay_bankName','$pay_trueName','$pay_cardNum','$pay_bankAccess','0','$time')");
			$this->checkApplyBank($uid,$pay_trueName,$pay_bankName,$pay_bankAccess,$pay_cardNum);
			if ($res) {
				$this->ajaxReturn(array('status' => 1),$this->json);
			}
			$this->ajaxReturn(array('status' => 0),$this->json);
		}else{
			$this->ajaxReturn(array('status' => 0),$this->json);
		}
	}
	
	private function checkApplyBank($uid,$pay_trueName,$pay_bankName,$pay_bankAccess,$pay_cardNum){
		$time=time();
		$res = $this->excq("SELECT * from `@#_share_apply_bank` where `uid`='$uid' and `truename`='$pay_trueName' and `cardAccess`='$pay_bankAccess' and `cardId`='$pay_cardNum' and `bankName`='$pay_bankName'  ");
		if(!$res){
			$ress=$this->aud("INSERT INTO `@#_share_apply_bank` ( `uid`, `trueName`, `bankName`, `cardId`, `cardAccess`, `time`) VALUES ( '$uid', '$pay_trueName', '$pay_bankName', '$pay_cardNum', '$pay_bankAccess', '$time');");
		}
	}
	private function getLevelUserInfo($userinfo,$level,$parentId){
		$userlist = array();
		foreach($userinfo as $key=>$vlaue){
			//p($vlaue);
			if($vlaue['level'] == $level){
				$userorder = $this->excq("SELECT sum(gain_price) as sum,count(*) count from `@#_distribution_log` where `uid`='{$parentId}' and `cid`='{$vlaue['uid']}'",2);
				$vlaue['countPrice'] =  round($userorder[0]['sum'],2);
				$vlaue['countOrder'] =  $userorder[0]['count'];
				$userlist[] =  $vlaue;
			}
		}
		return $userlist;
	}
	
	
	//所以下级信息
	private function allfansinfo(){
		$this->getUserinfo($this->jsonp);
		$member=$this->userinfo;
		$level=$this->fanslevel(intval($_GET['level_id']));
		$levelnumber=intval($_GET['level_id']);
		$webname=$level.'会员';
		$title=$level.'会员';
		$uid=$member['uid'];
		$userinfo = $this->excq("SELECT uid,yaoqing,mobile,img,username from `@#_member`",2);
		$fansinfo = $this->getMenuTree($userinfo,$member['uid'],3);
		$userlist = $this->getLevelUserInfo($fansinfo,$levelnumber,$member['uid']);
		//allInfo
		$this->ajaxReturn(array('status' => 1,'fansinfo' => $fansinfo,'userlist' => $userlist));
	}
	private function fansInfo($cid){
		$userInfo=$this->userinfo;
		$user= $this->excq("SELECT * FROM `@#_member` where `uid` = '$cid' limit 1");
		$user['orders']=$this->excq("SELECT * from `@#_distribution_log` where `cid`='{$cid}' and `uid`='{$userInfo['uid']}'",2);
		foreach( $user['orders'] as $key=>$value){
			$user['orders'][$key]['gain_price']=round($value['gain_price'],2);
			if($value['status']==0){
				$user['orders'][$key]['statu']='待清算';
	
			}elseif($value['status']==1){
				$user['orders'][$key]['statu']='已清算';
			}
		}
		return $user;
	}
	private function postMyBalance(){
		$this->getUserinfo();
		$Money = $_POST['Money'];
		$time=time();
		$userinfo = $this->userinfo;
		$uid = $userinfo['uid'];
		$applyPrice  = $this->checkApply();
		if($Money==$applyPrice &&$applyPrice>0){
			$type='1';
			$pay = '账户';
			$content = "邀请佣金兑现余额".$Money.'元';
			$money=$Money;
			$status='2';
			$username = $userinfo['username'];
			$res = $this->aud("INSERT INTO `@#_member_account` (`uid`,`type`,`pay`,`content`,`money`,`time`) value ('$uid','$type','$pay','$content','$money','$time') ");
			if($res){
				$this->aud("update `@#_member`  set `money`=money+'$money',`share_price`=share_price+'$money' where `uid`='$uid'");
				//$mysql_model->Query("update `@#_member`  set `share_price`=share_price+'$money' where `uid`='$uid'");
				$this->aud("INSERT INTO `@#_share_apply` (`uid`,`username`,`price`,`status`,`time`,`pay_type`)value('$uid','$username','$money','$status','$time','1')");
			}
			$this->ajaxReturn(array('status' => 1),$this->json);
		}else{
			$this->ajaxReturn(array('status' => 0),$this->json);
		}
	}
	
	
	private function allBank(){
		$bank=$this->excq("SELECT * from `@#_bank` order by sort desc",2);
		return $bank;
	}
	
	private function fanslevel($get){
		switch($get){
			case 1:
				return '一级';
				break;
			case 2:
				return '二级';
				break;
			case 3:
				return '三级';
				break;
			default:
				return '';
				break;
		}
	
	}
	
	private function checkApply(){
		$member=$this->userinfo;
		$uid = $member['uid'];
		$usersinfo = $this->excq("SELECT uid,yaoqing from `@#_member`",2);
		$usersApplyInfo = $this->excq("SELECT sum(price) as price from `@#_share_apply` where `uid`='$uid' and `status`='0'");
		$fansinfo = $this->getMenuTree($usersinfo,$member['uid'],3);
		$PriceInfo  = $this->getPriceICount($fansinfo,$member['uid']); //返回一个总佣金 和一个已完成的佣金  即单人夺宝的佣金
		//  $applyPrice = $PriceInfo['count']-$PriceInfo['wait']-$member['share_price']-$usersApplyInfo['price'];
		//  $applyPrice = $PriceInfo['count']-$member['share_price'];
		$applyPrice = $PriceInfo['count']-$member['share_price']-$PriceInfo['wait']-$usersApplyInfo['price'];
		$applyPrice =round($applyPrice,2);
		return $applyPrice;
	}
	
	private function applyInfo(){
		$member=$this->userinfo;
		$uid =$member['uid'];
		$arr=$this->excq("SELECT * from `@#_share_apply` where `uid`='$uid' order by time desc",2);
		foreach($arr as $key=>$value){
			if($value['status']==0){
				$arr[$key]['statu']='待审核';
			}elseif($value['status']==1){
				$arr[$key]['statu']='审核中';
			}elseif($value['status']==2){
				$arr[$key]['statu']='通过';
			}elseif($value['status']==3){
				$arr[$key]['statu']='失败';
			}
			$arr[$key]['time']=date('Y/m/d', $value['time']);
		}
		return $arr;
	}
	
	
	public function deleteBank(){
		$data =$_POST;
		$id=$data['id'];
		$res = $this->aud("delete  from  `@#_share_apply_bank` where `id`='{$id}'");
		echo $res;
	}
	
	private function allUserBank(){
		$member =$this->userinfo;
		$arr=$this->excq("SELECT * from `@#_share_apply_bank` where  `uid`='{$member['uid']}'",2);
		return $arr;
	}
	
	private function allfansorder(){
		$this->getUserinfo($this->jsonp);
		$fans_id = isset($_GET['fans_id']) ? intval($_GET['fans_id']) : 0;
		if (!$fans_id){
			$this->ajaxReturn(array('status' => 0,'msg' => '数据不存在'));
		}
		$userinfo=$this->fansInfo($fans_id);
		$order=$userinfo['orders']; //订单列表
		$title=$userinfo['username'].'订单列表';
		//allorder
		$this->ajaxReturn(array('status' => 1,'data' => $order,'title' => $title));
	}

	public function postapply(){
		$this->getUserinfo($this->jsonp);
		$bank=$this->allBank(); //bank Data
		$userBank =$this->allUserBank();
		$applyPrice = $this->checkApply();
		$applyOrderInfo = $this->applyInfo();
		$this->ajaxReturn(array('status' => 1,
				'bank' => $bank,
				'usebank' => $userBank,
				'applyprice' => $applyPrice,
				'orderinfo' => $applyOrderInfo
		));
	}
	/**
	 * @param $userinfo
	 * @param $uid
	 * @return array
	 * 获取佣金-1.总佣金，2.单人夺宝佣金，3.已完成组团夺宝佣金，4.未完成组团夺宝佣金
	 *
	 */
	private  function getPriceICount($userinfo,$uid){
		$arr = array();
		$count= $this->excq("SELECT sum(gain_price) as count from `@#_distribution_log` where `uid`='{$uid}'",2);
		$single  = $this->excq("SELECT sum(gain_price) as single from `@#_distribution_log` where  `uid`='{$uid}' and `status`=1 ",2);
	
		$arr['count'] = round($count[0]['count'],2);  //总佣金
		$arr['single'] = round($single[0]['single'],2); //单人和已完成的组团
		$arr['wait'] = round($arr['count']-$arr['single'],2);  //总佣金-单人和已完成的组团=未成的组团佣金

		//现在做到统计订单佣金
		return $arr;
	}
	
	private function getlevelcount($userinfo,$level){
		$arrTree = array(); //使用static代替global
		foreach($userinfo as $key=>$value){
			if($value['level']==$level){
				$arrTree[]=$value;
			}
	
		}
		return count($arrTree);
	}
	
	//最新揭晓
	private function tlottery(){
		//$FIdx=0;
		//$EIdx=10;
		$page = I('page',1,'intval');
		$isCount=1;
		$total=$this->excq("select COUNT(*) as c from `@#_teamgoods` where `q_uid` is not null and `q_showtime` = 'N'",2);
		$total = current($total)['c'];
		$getLimit = $this->getLimit($total,$page,10);
		$limit = $getLimit['limit'];
		$totalPage = $getLimit['totalPage'];
		//最新揭晓
		$shoplist['listItems']=$this->excq("select * from `@#_teamgoods` where `q_uid` is not null and `q_showtime` = 'N' ORDER BY `q_end_time` DESC $limit",2);
		if(empty($shoplist['listItems'])){
			$shoplist['code']=1;
		}else{
			foreach($shoplist['listItems'] as $key=>$val){
				//查询出购买次数
				$recodeinfo=$this->excq("select `gonumber` from `@#_member_team_record` where `uid` ='$val[q_uid]'  and `shopid`='$val[id]' and goucode LIKE '%{$val['q_user_code']}%'");
				$shoplist['listItems'][$key]['q_user']=get_user_name($val['q_uid']);
				$shoplist['listItems'][$key]['userphoto']=get_user_key($val['q_uid'],'img');
				$shoplist['listItems'][$key]['q_end_time']=microt($val['q_end_time']);
				$shoplist['listItems'][$key]['gonumber']=$recodeinfo['gonumber'];
			}
			$shoplist['code']=0;
			$shoplist['count']=$total;
			$shoplist['totalPage'] = $totalPage;
		}
	
		//获取倒计时商品
// 		$where = array('q_showtime' => 'Y');
// 		$timeList = M('teamgoods')->where($where)->order('q_end_time DESC')->limit(10)->select();
// 		foreach ($timeList as $key => $value) {
// 			$timeList[$key]['q_end_time'] = intval($value['q_end_time']-time());
// 		}
		$this->ajaxReturn($shoplist);
		
	}
	
	//直购、0元购
	private function free(){
		if (isset($_GET['type']) && $_GET['type'] == 'free'){
			$where = array('money' => 0);
		}else{
			$where = array('money' => array('NEQ',0));
		}
		$where = "`shenyurenshu`>0";
		$goods = M('jf_shoplist')->where($where)->field(array($this->zfield))->order('`order` asc')->select();
		$this->ajaxReturn(array('status' => 1,'data' => $goods));
	}
	//直购、0元
	private function z_item(){
		$goods_id = intval($_GET['goods_id']);
		if(!$goods_id){
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$item = M('jf_shoplist')->where(array('id' => $goods_id))->find();
		if ($item){
			$item['picarr'] = unserialize($item['picarr']);
			$this->ajaxReturn(array('status' => 1,'item' => $item));
		}
		$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
	}
	
	//免費搶購列表
	private function freego(){
		$where = "`isFree`=1 AND `q_uid` is null and `q_end_time` is null and `q_showtime`='N'";
		$goods = M('shoplist')->where($where)->field(array($this->field))->order('time desc')->select();
		$this->ajaxReturn(array('status' => 1,'data' => $goods));
	}
	
	//检测免费抢购权限
	private function checkprosissim(){
		$this->getUserinfo($this->jsonp);
		$goods_id = isset($_GET['goods_id'])?intval($_GET['goods_id']):0;
		if ($goods_id == 0 || !($goods = M('shoplist')->where(array('id' => $goods_id))->find())){
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		
		//0新手夺宝 1逆袭夺宝 2 特惠夺宝
		if ($goods['freetype'] == 0){
			$time = time()-$this->userinfo['time'];
			//if ($time < intval($goods['registerDay'])*3600*24){
			//$this->ajaxReturn(array('status' => 0,'msg' => '新手夺宝注册满'.$goods['registerDay'].'天才能购买'));
			if ($time/86400 != $goods['registerDay']){//天内的新会员才能参与此商品夺宝
				$this->ajaxReturn(array('status' => 0,'msg' => '注册超过'.$goods['registerDay'].'天'));
			}
		}
		
		if ($goods['freetype'] == 1){
			//$ids = M('shoplist')->where(array('sid' => $goods['sid']))->getField('id');
			$shopinfo = M('Member_go_record')->where(array('uid' => $this->userinfo['uid'],'huode' => array('NEQ','0')))->count();
			if (!empty($shopinfo)){
				$this->ajaxReturn(array('status' => 0,'msg' => '您已经中过奖不能购买'));
			}
		}
		
		if ($this->userinfo['score'] < 50){
			$this->ajaxReturn(array('status' => 0,'msg' => '您的福分不足'));
		}
		//购物商品,最少推荐注册人数
		if ($this->userinfo['invite_num'] < $goods['freeMin']){
			$this->ajaxReturn(array('status' => 0,'msg' => '邀请人数不足'));
		}
		$gonumber = 0;
		$gonumber = M('member_go_record')
		->where(array('uid' => $this->userinfo['uid'],'shopid' => $goods_id))->sum('gonumber');
		if (($goods['freeMax']-$gonumber) <= 0){
			$this->ajaxReturn(array('status' => 0,'msg' => "您购买人次有限"));
		}
		if (intval($_GET['num']) > ($goods['freeMax']-$gonumber)){
			$a = $goods['freeMax']-$gonumber;
			$this->ajaxReturn(array('status' => 0,'msg' => "只能购物买{$a}人次"));
		}
		
		$this->ajaxReturn(array('status' => 1,'msg' => 'ok'));
		//最多可以参与多少人次
		//$goods['freeMax'];
		//夺宝类型
		//$goods["freetype"];
	}
	
	//免費搶購商品詳情
	private function f_item(){
		$goods_id = intval($_GET['goods_id']);
		if(!$goods_id){
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$item = M('shoplist')->where(array('id' => $goods_id))->find();
		if ($item){
			$item['picarr'] = unserialize($item['picarr']);
			//晒单数
			$shoplist=$this->excq("select * from `@#_shoplist` where `sid`='$item[sid]'",2);
			$shop='';
			foreach($shoplist as $list){
				$shop.=$list['id'].',';
			}
			$id=trim($shop,',');
			if($id){
				$shaidan=$this->excq("select * from `@#_shaidan` where `sd_shopid` IN ($id)",2);
				$sum=0;
				foreach($shaidan as $sd){
					$shaidan_hueifu=$this->excq("select * from `@#_shaidan_hueifu` where `sdhf_id`='$sd[sd_id]'",2);
					$sum=$sum+count($shaidan_hueifu);
				}
			}else{
				$shaidan=0;
				$sum=0;
			}
			$this->ajaxReturn(array('status' => 1,'item' => $item,
					'sunOrder' => array('count' => count($shaidan),'comment' => $sum)
			));
		}
		$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
	}
	
	//购物车商品列表
	private function zcartlist(){
		$otherData = $this->__zcart();
		$this->ajaxReturn(array('shop' => $otherData['shop'],'shoplist' => $otherData['shoparr'],'MoenyCount' => $otherData['MoenyCount']),'json');
	}

	private function __zcart(){
		$cartJSON = isset($_POST['cart'])?$_POST['cart']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
		if($shopids!=NULL){
			$ids = explode(',', $shopids);
			$shoparr=$this->excq("SELECT {$this->zfield} FROM `".C('DB_PREFIX')."jf_shoplist` where `id` in($shopids)",3,$ids);
		}
		foreach ($shoparr as $key => $value) {
			if ($Mcartlist[$key]){
				$shoparr[$key]['cart_xiaoji'] = $Mcartlist[$key]['num']*$value['money'];
				$shoparr[$key]['cart_gorenci'] = $Mcartlist[$key]['num'];
				if ($value['money'] == 0){
					$shoparr[$key]['cart_freight'] = $Mcartlist[$key]['num']*$value['yunjiage'];
				}else{
					$shoparr[$key]['cart_freight'] = $value['yunjiage'];
				}
			}
		}
		$MoenyCount = 0;
		$shop = 0;
		if(count($shoparr) > 0){
			$shop = 1;
			foreach ($shoparr as $key => $value){
				$MoenyCount += $value['cart_xiaoji']+$value['cart_freight'];
			}
		}
		// 总支付价格
		$MoenyCount = substr( sprintf ( "%.3f", $MoenyCount), 0, - 1 );
		return array('MoenyCount' => $MoenyCount,'shop' => $shop,'shoparr' => $shoparr);
	}
	
	//提交订单成功并充值成功，继续付款
	private function zgopayment(){
		$this->is_check_postCart();
		if (empty($_POST['code']) || empty($_POST['money']) || $_POST['money'] <= 0){
			$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
		}
		$pay_type = '支付宝';
		if($_POST['pay_type'] == 'wapalipay'){
			$pay_type = '支付宝';
		}elseif ($_POST['pay_type'] == 'wxpay_web'){
			$pay_type = '微支付';
		}
	
		if(!isset($_POST['pay_type'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '请选择支付平台'),'json');
		}
		$fufen = isset($_POST['score'])?$_POST['score']:''; // 获取福分
		$pay = new pay();// 购买商品
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$pay->fufen = 0;
		$pay->pay_type_bank = $_POST['pay_type'];
		//提交订单时间，实时检测商品
		$check = $pay->init($this->userinfo['uid'],0,'zf_record');
		if (is_array($check)){
			$data = array(
					'code' => I('post.code'),
					'money' => I('post.money'),
					'pay_type' => $pay_type,
					'status' => '未付款',
					'uid' => $this->userinfo['uid'],
					'time' => NOW_TIME,
					'score' => 0,
					'scookies' => $_POST['cart'],
			);
			if (!M('member_addmoney_record')->add($data)){
				$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
			}
			$this->ajaxReturn(array('status' => 1,'msg' => 'ok'),'json');
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => $check),'json');
		}
	}
	
	//结算页面
	private function zpayment(){
		$this->getUserinfo();
		$otherData = $this->__zcart();
		// 会员余额
		$Money = $this->userinfo['money'];
		// 商品数量
		$shoplen = count($otherData['shoparr']);
		$paylist = $this->excq("SELECT * FROM `@#_pay` where `pay_start` = '1' AND pay_mobile = 1",2);
		$alipay_key = require_once APP_CORE.'/config/key.inc.php';
		foreach ($paylist as $key => $value){
			$pay_key = unserialize($value['pay_key']);
			if($value['pay_class'] == 'wapalipay'){
				$paylist[$key]['pay_partner'] = $pay_key['id']['val'];
				$paylist[$key]['pay_key'] = $pay_key['key']['val'];
				$paylist[$key]['pay_account'] = $pay_key['user']['val'];
				$paylist[$key]['public_key'] = $alipay_key['alipay']['public_key'];
				$paylist[$key]['private_key'] = $alipay_key['alipay']['private_key'];
			}elseif ($value['pay_class'] == 'wxpay_web'){
				$paylist[$key]['pay_partner'] = $pay_key['APPID']['val'];
				$paylist[$key]['pay_key'] = $pay_key['KEY']['val'];
				$paylist[$key]['pay_account'] = $pay_key['MCHID']['val'];
			}
		}
		$payhtml = '';
		foreach ($paylist as $key => $value) {
			$payhtml .= '<li class="gray9 select_pay" urm="'.$value['pay_id'].'"><i><s></s>';
			$checked = '';
			$css = "";
			if($value['pay_class'] == 'wapalipay'){
				$checked = 'checked="checked"';
				$css = 'class="selectedP"';
			}
			$payhtml .= '<input id="'.$value['pay_id'].'" item="'.$value['pay_class'].'" class="regular-radio" '.$checked.' type="radio" value="'.$value['pay_id'].'" name="account" id="'.$value['pay_class'].'">';
			$payhtml .= '<label for="'.$value['pay_id'].' '.$css.'"></label></i>'.$value['pay_name'].'</li>';
		}
	
		$address = M('member_dizhi')->where(array('uid' => $this->userinfo['uid'],'default' => 'Y'))->find();
		
		$this->ajaxReturn(array('status' => 1,
				'money' => $Money,
				'hidPoints' => $this->userinfo['score'],
				'count'=> $shoplen,
				'payapi' => $paylist,
				'paylist' => $payhtml,
				'pay_type' => $Money>=$otherData['MoenyCount']?'ok':'error',
				'shoplist' => $otherData['shoparr'],
				'address' => empty($address)?'no':$address,
				'MoenyCount' => $otherData['MoenyCount']),'json');
	}
	
	//0元购，直购，余额支付
	private function zpaysubmit() {
		$this->is_check_postCart();
		$checkpay = isset($_POST['checkpay'])?$_POST['checkpay']:''; // 获取支付方式 fufen money bank
		$banktype = isset($_POST['banktype'])?$_POST['banktype']:''; // 获取选择的银行 CMBCHINA ICBC CCB
		$money = isset($_POST['money'])?$_POST['money']:''; // 获取需支付金额
		$fufen = isset($_POST['score'])?$_POST['score']:''; // 获取福分
		$isBag = isset($_POST['bag'])?$_POST['bag']:'a';
		$uid = $this->userinfo ['uid'];
		$zhifutype = $this->excq("select * from `@#_pay` where `pay_class` = 'alipay'");
		if (!$zhifutype) {
			$this->ajaxReturn(array('status' => 0,'msg' => '请使用微支付或支付宝'),'json');
		}
		$pay_checkbox = false; //钱包支付
		$pay_type_bank = false; //银行卡支付
		$pay_type_id = false;   //获取平台支付类型，支付宝，微信支付...
		if ($checkpay == 'money') {
			$pay_checkbox = true;
		}
		//不是银行
		if ($banktype != 'nobank') {
			$pay_type_id = $banktype; //支付类型的id
		}
		if (! empty ($zhifutype)) {
			$pay_type_bank = $zhifutype['pay_class'];
		}
		if (!$pay_type_id) {
			if ($checkpay != 'fufen' && $checkpay != 'money'){
				$this->ajaxReturn(array('status' => 0,'msg' => '请使用微支付或支付宝2'),'json');
			}
		}
		$pay = new pay();// 购买商品
		$pay->pay_type_str = $isBag;
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$pay->fufen = $checkpay == 'fufen'?$fufen:0;
		$pay->pay_type_bank = $pay_type_bank;
		//提交订单时间，实时检测商品
		$checkGoods = $pay->init($uid,$pay_type_id,'zf_record');
		if (is_array($checkGoods)){
			//以上全检测通过后，进入，支付，生成订单号
			$check = $pay->zf_go_pay();
			if (!$check){
				$this->ajaxReturn(array('status' => 0,'msg' => '订单添加失败'),'json');
			}
			if ($check) {
				// 成功
				$this->ajaxReturn(array('status' => 1,'msg' => '购买成功'),'json');
			} else {
				// 失败
				$this->ajaxReturn(array('status' => 0,'msg' => '订单添加失败'),'json');
			}
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => $checkGoods),'json');
		}
	}
	
	//直购订单
	private function zrecord(){
		$this->getUserinfo($this->jsonp);
		if (isset($_GET['type']) && $_GET['type'] == 'all'){
			$where = 'jf.shopid=shop.id and shop.money>0 and jf.uid='.$this->userinfo['uid'];
		}elseif (isset($_GET['type']) && $_GET['type'] == 'action'){
			$where = "jf.shopid=shop.id and shop.money>0 and jf.uid={$this->userinfo['uid']} and jf.status='已付款,未发货,未完成'";
		}elseif (isset($_GET['type']) && $_GET['type'] == 'sendout'){
			$where = "jf.shopid=shop.id and shop.money>0 and jf.uid={$this->userinfo['uid']} and jf.status='已付款,已发货,待收货'";
		}elseif (isset($_GET['type']) && $_GET['type'] == 'finish'){
			$where = "jf.shopid=shop.id and shop.money>0 and jf.uid={$this->userinfo['uid']} and jf.status='已付款,已发货,已完成'";
		}elseif (isset($_GET['type']) && $_GET['type'] == 'void'){
			$where = "jf.shopid=shop.id and shop.money>0 and jf.uid={$this->userinfo['uid']} and jf.status like '%已作废%'";
		}
		//$order = M('member_go_jf_record')->where($where)->order('time desc')->select();
		$sql = "select jf.* from `@#_member_go_jf_record` as jf,`@#_jf_shoplist` as shop where $where order by jf.id DESC";
		$order = $this->excq($sql,2);
		if (!empty($order)){
			$model = M('jf_shoplist');
			foreach ($order as $key => $value) {
				$order[$key]['thumb'] = $model->where(array('id' => $value['shopid']))->getField('thumb');
				$order[$key]['time'] = date('Y-m-d H:i:s',$value['time']);
			}
		}
		$this->ajaxReturn(array('status' => 1,'count' => count($order),'data' => $order));
	}
	
	//免费购订单
	private function zrecord2(){
		$this->getUserinfo($this->jsonp);
		if (isset($_GET['type']) && $_GET['type'] == 'all'){
			$where = 'jf.shopid=shop.id and shop.money=0 and jf.uid='.$this->userinfo['uid'];
		}elseif (isset($_GET['type']) && $_GET['type'] == 'action'){
			$where = "jf.shopid=shop.id and shop.money=0 and jf.uid={$this->userinfo['uid']} and jf.status='已付款,未发货,未完成'";
		}elseif (isset($_GET['type']) && $_GET['type'] == 'sendout'){
			$where = "jf.shopid=shop.id and shop.money=0 and jf.uid={$this->userinfo['uid']} and jf.status='已付款,已发货,待收货'";
		}elseif (isset($_GET['type']) && $_GET['type'] == 'finish'){
			$where = "jf.shopid=shop.id and shop.money=0 and jf.uid={$this->userinfo['uid']} and jf.status='已付款,已发货,已完成'";
		}elseif (isset($_GET['type']) && $_GET['type'] == 'void'){
			$where = "jf.shopid=shop.id and shop.money=0 and jf.uid={$this->userinfo['uid']} and jf.status like '%已作废%'";
		}
		//$order = M('member_go_jf_record')->where($where)->order('time desc')->select();
		$sql = "select jf.* from `@#_member_go_jf_record` as jf,`@#_jf_shoplist` as shop where $where order by jf.id DESC";
		$order = $this->excq($sql,2);
		if (!empty($order)){
			$model = M('jf_shoplist');
			foreach ($order as $key => $value) {
				$order[$key]['thumb'] = $model->where(array('id' => $value['shopid']))->getField('thumb');
				$order[$key]['time'] = date('Y-m-d H:i:s',$value['time']);
			}
		}
		$this->ajaxReturn(array('status' => 1,'count' => count($order),'data' => $order));
	}
	
	//0元购，直购
	private function zbuydetail(){
		$this->getUserinfo($this->jsonp);
		if (isset($_GET['orderid']) && intval($_GET['orderid'])){
			$where = array('id' => intval($_GET['orderid']),'uid' => $this->userinfo['uid']);
			$order = M('member_go_jf_record')->where($where)->find();
			if(!empty($order)){
				$order['thumb'] = M('jf_shoplist')->where(array('id' => $order['shopid']))->getField('thumb');
				$order['time'] = date('Y-m-d H:i:s',$order['time']);
			}
			$this->ajaxReturn(array('status' => 1,'data' => $order));
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '数据不存在'));
		}
	}
	
	//代理商二维码
	//生成二维码
	private function wxcode(){
		$this->getUserinfo($this->jsonp);
		$PNG_TEMP_DIR = dirname(ROOT_PATH).DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.'qrcode'.DIRECTORY_SEPARATOR;
		$PHPQRCODE_PATH = ROOT_PATH.DIRECTORY_SEPARATOR.'phpqrcode'.DIRECTORY_SEPARATOR;
		include $PHPQRCODE_PATH."qrlib.php";
		if (!file_exists($PNG_TEMP_DIR)){
			mkdir($PNG_TEMP_DIR,0777);
		}
		$filename = $PNG_TEMP_DIR.'test.png';
		 
		$errorCorrectionLevel = 'L';
		if (isset($_REQUEST['level']) && in_array($_REQUEST['level'], array('L','M','Q','H')))
			$errorCorrectionLevel = $_REQUEST['level'];
		 
		$matrixPointSize = 5;
		if (isset($_REQUEST['size'])){
			$matrixPointSize = min(max((int)$_REQUEST['size'], 1), 10);
		}
		 
		$reg_rul = W_WEB_PATH."/mobile/user/register/".$_GET['uid'];
		$file = 'u'.$this->userinfo['uid'].md5($this->userinfo['uid'].'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
		$filename = $PNG_TEMP_DIR.$file;
		if (!file_exists($filename)){
			QRcode::png($reg_rul, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
		}
		$qrcode = G_WEB_PATH.'/qrcode/'.$file;
		$this->ajaxReturn(array('status' => 1,'file' => $qrcode));
	}
	
	//
	private function tsinglelist(){
		$this->getUserinfo($this->jsonp);
		$FIdx=0;
		$EIdx=10;
		$member=$this->userinfo;
		
		if(isset($_GET['sd_ok_id']) && intval($_GET['sd_ok_id']) != 0){
			$order_id = intval($_GET['sd_ok_id']);
			$goods_id = M('member_team_record')->where(array('id' => $order_id))->getField('shopid');
			$map = ' and a.sd_shopid='.$goods_id;
			$postlist['listItems'] = $this->excq("select * from `@#_shaidan` a left join `@#_teamgoods` b on a.sd_shopid=b.id where a.sd_userid='$member[uid]' $map limit 1");
			$list = false;
		}else{
			$list = true;
			$postlist['listItems'] = $this->excq("select * from `@#_shaidan` a left join `@#_teamgoods` b on a.sd_shopid=b.id where a.sd_userid='$member[uid]' and a.sd_type='1' order by a.sd_time desc",2);
		}
		
		if(empty($postlist['listItems'])){
			$postlist['code']=1;
		}else{
			if ($list){
				foreach($postlist['listItems'] as $key=>$val){
					$postlist['listItems'][$key]['sd_time']=date('Y-m-d H:i',$val['sd_time']);
				}
			}else{
				$postlist['listItems']['sd_time']=date('Y-m-d H:i',$postlist['listItems']['sd_time']);
			}
			$postlist['code']=0;
		}
		$this->ajaxReturn(array('status' => 1,'data' => $postlist));
	}
	
	private function tsinglelister(){
		$this->getUserinfo($this->jsonp);
		$member=$this->userinfo;
		$cord=$this->excq("select * from `@#_member_team_record` where `uid`='$member[uid]' and `huode` > '10000000'",2);
		$shaidan=$this->excq("select * from `@#_shaidan` where `sd_userid`='$member[uid]' and `sd_type`='1' order by `sd_id`",2);
		$sd_id = $r_id = array();
		foreach($shaidan as $sd){
			if(!empty($sd['sd_shopid'])){
				$sd_id[]=$sd['sd_shopid'];
			}
		}
		foreach($cord as $rd){
			if(!in_array($rd['shopid'],$sd_id)){
				$r_id[]=$rd['shopid'];
			}
		}
		if(!empty($r_id)){
			$rd_id=implode(",",$r_id);
			$rd_id = trim($rd_id,',');
		}else{
			$rd_id="0";
		}
	
		$record = $this->excq("select a.shopid,a.id as aid,b.* from `@#_member_team_record` as a left join `@#_teamgoods` as b on a.shopid=b.id where a.shopid in ($rd_id) and a.`uid`='$member[uid]' and a.`huode`>'10000000' and b.q_showtime='N'",2);
		$this->ajaxReturn(array('status' => 1,'data' => $record));
	}
	
	//ajax获取组团记录
	private function getteamrecord(){
		$this->getUserinfo($this->jsonp);
		$page =  isset($_GET['page']) ? intval($_GET['page']) : 1; //默认1
		$type = isset($_GET['type']) ? $_GET['type'] : 'all';
		$member = $this->userinfo;
		$model = M('teamgoods');
		$where = array('q_create_uid' => $member['uid']);
		if ($type == 'action'){
			$where['q_uid'] = array('EXP','is not null');
			$where['q_showtime'] = 'Y';
			$goods = $model->where($where)
			->field(array('title','sid','qishu','yunjiage','q_uid','q_end_time','q_user','q_user_code','zongrenshu','canyurenshu','shenyurenshu','money','id','thumb','q_create_time','q_create_uid','q_group_name','q_create_pwd'))
			->order('id DESC')->select();
			if (empty($goods)){
				$goods = array();
			}
				
			$map = array('q_create_uid' => $member['uid'],'shenyurenshu' => array('NEQ',0));
			$temp = $model->where($map)
			->field(array('title','sid','qishu','yunjiage','q_uid','q_end_time','q_user','q_user_code','zongrenshu','canyurenshu','shenyurenshu','money','id','thumb','q_create_time','q_create_uid','q_group_name','q_create_pwd'))
			->order('id DESC')->select();
			if (empty($temp)) {
				$temp = array();
			}
			$goods = array_merge($goods,$temp);
			if(!empty($goods)){
				foreach ($goods as $key => $value) {
					if ($value['q_end_time']){
						$goods[$key]['q_end_time'] = microt($value['q_end_time']);
					}
				}
			}
			$goods[0]['num'] = count($goods);
			$this->ajaxReturn($goods);
			exit;
		}elseif ($type == 'show'){
			$where['q_uid'] = array('EXP','is not null');
			$where['q_showtime'] = 'N';
		}
	
			
		//0,10 10,10
		$pageSize = 10;
		$total = $model->where($where)->count();
		$totalPage = ceil($total/$pageSize);
		if ($page == 1){
			$start = 1;
		}elseif ($page > 1){
			$start = $page;
		}
		$limit = ($start-1)*$pageSize.','.$pageSize;
		$goods = array();
		$goods = $model->where($where)
		->field(array('title','sid','qishu','yunjiage','q_uid','q_end_time','q_user','q_user_code','zongrenshu','canyurenshu','shenyurenshu','money','id','thumb','q_create_time','q_group_name','q_create_pwd'))
		->limit($limit)->order('id DESC')->select();
		if(!empty($goods)){
			foreach ($goods as $key => $value) {
				if ($value['q_end_time']){
					$goods[$key]['q_end_time'] = microt($value['q_end_time']);
				}
			}
		}
		$goods[0]['num'] = count($goods);
		$this->ajaxReturn($goods);
	}
	
	//获取团购记录
	private function ajaxgetrecord(){
		$this->getUserinfo($this->jsonp);
		$member=$this->userinfo;
		$uid = $member['uid'];
		$type = !empty($_GET['type']) ? $_GET['type'] : 'action';
		if ($type == 'action'){
			$record = array();
			$record = $this->excq("select a.*,b.thumb,b.zongrenshu,b.canyurenshu from `@#_member_team_record` a left join `@#_teamgoods` b on a.shopid=b.id where a.uid='$uid' and b.q_uid is null order by a.id DESC",2);
			$record2 = array();
			$record2 = $this->excq("select a.*,b.thumb,b.zongrenshu,b.canyurenshu from `@#_member_team_record` a left join `@#_teamgoods` b on a.shopid=b.id where a.uid='$uid' and b.q_uid is not null and b.q_showtime='Y' order by a.id DESC",2);
			$record = array_merge($record,$record2);
		}elseif ($type == 'show'){
			$record = $this->excq("select a.*,b.thumb,b.zongrenshu,b.canyurenshu,b.q_user_code,b.q_end_time from `@#_member_team_record` a left join `@#_teamgoods` b on a.shopid=b.id where a.uid='$uid' and b.q_uid is not null and b.q_showtime='N' order by a.id DESC",2);
			foreach ($record as $key => $value) {
				$record[$key]['q_end_time'] = microt($value['q_end_time']);
			}
		}
		$record[0]['num'] = count($record);
		$this->ajaxReturn($record);
	}
	
	//团获得的商品
	private function teamgetorlist(){
		$this->getUserinfo($this->jsonp);
		$FIdx=isset($_GET['page'])?intval($_GET['page']):1;
		$EIdx=10;
		$member=$this->userinfo;
		$order=$this->excq("select * from `@#_member_team_record` a left join `@#_teamgoods` b on a.shopid=b.id where b.q_showtime='N' and b.q_uid='$member[uid]'",2);
		$orderlist['listItems']=$this->excq("select * from `@#_member_team_record` a left join `@#_teamgoods` b on a.shopid=b.id where b.q_uid='$member[uid]' and b.q_showtime='N' and a.huode!=0 order by a.time desc",2);
		if(empty($orderlist['listItems'])){
			$orderlist['code']=1;
		}else{
			foreach($orderlist['listItems'] as $key=>$val){
				$orderlist['listItems'][$key]['q_end_time']=microt($val['q_end_time']);
			}
			$orderlist['code']=0;
		}
		$orderlist['count']=count($order);
		$this->ajaxReturn($orderlist);
	}
	
	//我的粉丝
	private function myfans(){
		$this->getUserinfo($this->jsonp);
		$member=$this->userinfo;
		$year = date('Y');
		$month = date('m');
		$str = $year.'-'.$month.'-01';
		$start_time = strtotime($str);
		$field = "uid,type,level_id,qianming,username,truename,email,mobile,img,time,city,province,area";
		//$user = $this->db->GetList("select $field from `@#_member` where `agentyaoqing`='{$member['uid']}' and `time`>= '$start_time'");
		$user = $this->excq("select $field from `@#_member` where `agentyaoqing`='{$member['uid']}' order by time desc",2);
		$count = 0;
		foreach ($user as $key => $value) {
			$user[$key]['username'] = get_user_name($value['uid']);
			$user[$key]['time'] = date('Y-m-d H:i:s',$value['time']);
			$find = $this->excq("select sum(gonumber) as count from `@#_member_go_record` where `uid`='{$value['uid']}'");
			$count = $find['count'];
			$tfind = $this->excq("select sum(gonumber) as count from `@#_member_team_record` where `uid`='{$value['uid']}'");
			$count2 = $tfind['count'];
			$totalCount = $count+$count2;
			$user[$key]['buy_count'] = $totalCount?$totalCount:0;
		}
		$this->ajaxReturn(array('status' => 1,'data' => $user,'count' => count($user)));
	}
	

	//代理商申请佣金提现
	private function agentcashout(){
		if (isset($_POST['send'])){
			$this->getUserinfo();
		}else{
			$this->getUserinfo($this->jsonp);
		}
		$member = $this->userinfo;
		$model = M('member_agent_recodes');
		//累计收入总金额
		$total_money = $model->where(array('agent_id' => $this->userinfo['uid'],'type' => 1))->sum('money');
		//累计转入总金额
		$z_total_money = $model->where(array('uid' => $member['uid'],'type' => 4))->sum('money');
	
		//提现冻结总金额
		$model_out = M('member_agent_cashout');
		$disabled_money = $model_out->where(array('uid' => $this->userinfo['uid'],'auditstatus' => 0))->sum('money');
	
		//提现通过总金额
		$outcash_ok_money = $model_out->where(array('uid' => $this->userinfo['uid'],'auditstatus' => 1))->sum('money');
	
		//活动佣金
		$active_price = $total_money-$z_total_money-$disabled_money-$outcash_ok_money;
		
		$active_price = $active_price > 0 ? $active_price : 0;
		
		if(isset($_POST['send'])){ //提现
			$money      = abs(intval($_POST['money']));
			if (!$money || $money < 100){
				$this->ajaxReturn(array('status' => 0,'msg' => '佣金金额大于100元才能提现'),$this->json);
			}
			$username   =htmlspecialchars($_POST['txtUserName']);
			if (empty($username)){
				$this->ajaxReturn(array('status' => 0,'msg' => '开户人不能为空'),$this->json);
			}
			$bankname   =htmlspecialchars($_POST['txtBankName']);
			if (empty($bankname)){
				$this->ajaxReturn(array('status' => 0,'msg' => '银行名称不能为空'),$this->json);
			}
			$branch     =htmlspecialchars($_POST['txtSubBank']);
			if (empty($branch)){
				$this->ajaxReturn(array('status' => 0,'msg' => '开户支行不能为空'),$this->json);
			}
			$banknumber =htmlspecialchars($_POST['txtBankNo']);
			if (empty($banknumber)){
				$this->ajaxReturn(array('status' => 0,'msg' => '银行帐号不能为空'),$this->json);
			}
			$linkphone  =htmlspecialchars($_POST['txtPhone']);
			if (empty($linkphone)){
				$this->ajaxReturn(array('status' => 0,'msg' => '联系电话不能为空'),$this->json);
			}
			if (!_checkmobile($linkphone)){
				$this->ajaxReturn(array('status' => 0,'msg' => '联系电话不正确'),$this->json);
			}
	
			$time       =time();
			$type       = 2;  //收取1/消费-1/充值-2/提现2
			if($total_money < 100){
				$this->ajaxReturn(array('status' => 0,'msg' => '佣金金额大于100元才能提现'),$this->json);
			}elseif($active_price < $money){
				$this->ajaxReturn(array('status' => 0,'msg' => '输入额超出可提现佣金金额'),$this->json);
			}elseif($total_money<$money ){
				$this->ajaxReturn(array('status' => 0,'msg' => '输入额超出总佣金金额'),$this->json);
			}else{
				//插入提现申请表  这里不用在佣金表中插入记录 等后台审核才插入
				$this->aud("INSERT INTO `@#_member_agent_cashout`(`uid`,`money`,`username`,`bankname`,`branch`,`banknumber`,`linkphone`,`auditstatus`,`time`)VALUES
						('{$member['uid']}','$money','$username','$bankname','$branch','$banknumber','$linkphone','0','$time')");
						$out_id = $this->insert_id;
						if ($out_id){
						$query_1 = $this->aud("insert into `@#_member_agent_recodes` (uid,agent_id,type,content,money,cashoutid,time) values ('{$this->userinfo['uid']}','{$this->userinfo['uid']}','$type','提现','$money','$out_id','$time')");
						if ($query_1){
						$this->ajaxReturn(array('status' => 1,'msg' => '申请成功！请等待审核'),$this->json);
						}
						}
				}
			}
				
			$this->ajaxReturn(array(
					'status' => 1,
					'total_money' => $total_money?$total_money:0,
					'z_money' => $z_total_money+$disabled_money+$outcash_ok_money,
					'active_price' => $active_price,
					'send' => $active_price>100?'ok':'no',
			));
						
	}
	
	
	private function fansrecord(){
		$this->getUserinfo($this->jsonp);
		$member = $this->userinfo;
		$year = date('Y');
		$month = date('m');
		$str = $year.'-'.$month.'-01';
		$start_time = strtotime($str);
		//$where = "`time`>$start_time and `agent_id`='{$member['uid']}' and `type`='1'";
		$where = "`agent_id`='{$member['uid']}' and `type`='1'";
		$field = "uid,type,level_id,username,truename,email,mobile,img,time,city,province,area";
		$getAll = $this->excq("select uid,money,ygmoney from `@#_member_agent_recodes` where $where order by `time` desc",2);
		$count_num = count($getAll);
		$price = 0;
		foreach ($getAll as $key => $value){
			$price += $value['ygmoney'];
		}
		//$page = getPage($count_num, 20);
		$list = $this->excq("select * from `@#_member_agent_recodes` where $where order by `time` desc",2);		
		foreach ($list as $key => $value) {
			$list[$key]['uimg'] = get_user_name($value['uid'],'img');
			$list[$key]['uname'] = get_user_name($value['uid']);
			$list[$key]['uid'] = $value['uid'];
			if (!$value['bl']){
				$value[$key]['bl'] = 0;
			}
		}
		$this->ajaxReturn(array('status' => 1,'data' => $list,'price' => $price));
	}
	
	private function fansrecords(){
		$this->getUserinfo($this->jsonp);
		$member = $this->userinfo;
		/*
		$year = date('Y');
		$month = date('m');
		$str = $year.'-'.$month.'-01';
		$start_time = strtotime($str);
		*/
		$where = "`agent_id`='{$member['uid']}' and `type`='1'";
		$field = "uid,type,level_id,username,truename,email,mobile,img,time,city,province,area";
		$getAll = $this->excq("select uid,money,ygmoney from `@#_member_agent_recodes` where $where order by `time` desc",2);
		$count_num = count($getAll);
		$price = 0;
		foreach ($getAll as $key => $value){
			$price += $value['ygmoney'];
		}
		$list = $this->excq("select * from `@#_member_agent_recodes` where $where order by `time` desc",2);
		foreach ($list as $key => $value) {
			$list[$key]['uimg'] = get_user_name($value['uid'],'img');
			$list[$key]['uname'] = get_user_name($value['uid']);
			$list[$key]['uid'] = $value['uid'];
			$list[$key]['time'] = date('Y-m-d H:i:s',$value['time']);
			if (!$value['bl']){
				$list[$key]['bl'] = 0;
			}
		}
		$this->ajaxReturn(array('status' => 1,'data' => $list,'price' => $price));
	}
	
	//代理佣金管理
	private function cashmanage(){
		$this->getUserinfo($this->jsonp);
		$member=$this->userinfo;
		$list = $this->excq("SELECT SUM(money) as count,SUM(ygmoney) as count2, date_format(FROM_UNIXTIME(`time`),'%Y-%m') as time FROM `@#_member_agent_recodes` where type=1 and agent_id={$member['uid']} group by uid",2);
	
		//累计收入总金额
		$total_money = M('member_agent_recodes')->where(array('agent_id' => $this->userinfo['uid'],'type' => 1))->sum('money');
		//累计转入总金额
		$z_total_money = M('member_agent_recodes')->where(array('uid' => $this->userinfo['uid'],'type' => 4))->sum('money');
		//提现冻结总金额
		$model_out = M('member_agent_cashout');
		$disabled_money = $model_out->where(array('uid' => $this->userinfo['uid'],'auditstatus' => 0))->sum('money');
		//提现通过总金额
		$outcash_ok_money = $model_out->where(array('uid' => $this->userinfo['uid'],'auditstatus' => 1))->sum('money');
		//转入、提现
		$z_out_total_money = $z_total_money+$disabled_money+$outcash_ok_money;
		//计算可用金额  = 累计收入总金额-累计转入总金额
		$enable_money =  $total_money-$z_out_total_money > 0 ? $total_money-$z_out_total_money : 0;
		$this->ajaxReturn(array('status' => 1,'enable_money' => $enable_money,'data' => $list));
	}
	
	//代理佣金转入账户
	private function intoaccount(){
		$this->getUserinfo($this->jsonp);
		if($this->userinfo['type'] == 1 && $this->userinfo['level_id'] > 0){
			$where = "`agent_id`='{$this->userinfo['uid']}' and `type`='1'";
			//累计收入总金额
			$total_money = M('member_agent_recodes')->where(array('agent_id' => $this->userinfo['uid'],'type' => 1))->sum('money');
			//累计转入总金额
			$z_total_money = M('member_agent_recodes')->where(array('uid' => $this->userinfo['uid'],'type' => 4))->sum('money');
			//提现冻结总金额
			$model_out = M('member_agent_cashout');
			$disabled_money = $model_out->where(array('uid' => $this->userinfo['uid'],'auditstatus' => 0))->sum('money');
	
			//提现通过总金额
			$outcash_ok_money = $model_out->where(array('uid' => $this->userinfo['uid'],'auditstatus' => 1))->sum('money');
	
			//转入、提现
			$z_out_total_money = $z_total_money+$disabled_money+$outcash_ok_money;
	
			if ($z_out_total_money >= $total_money){
				$this->ajaxReturn(array('status' => 0,'msg' => '无佣金可用'));
			}
	
			//计算可用金额  = 累计收入总金额-累计转入总金额
			$enable_money = $total_money-$z_out_total_money;
			$time = time();
			$model = new CoreModel();
			$model->startTrans();
			$query_1 = $this->aud("insert into `@#_member_agent_recodes` (uid,agent_id,type,content,money,time) values ('{$this->userinfo['uid']}','{$this->userinfo['uid']}','4','转入账户','$enable_money','$time')");
			$query_2 = $this->aud("insert into `@#_member_account` (uid,type,pay,content,money,time) values ('{$this->userinfo['uid']}','1','账户','粉丝消费获得佣金，转入佣金','$enable_money','$time')");
			if ($query_1 && $query_2){
				$model->commit();
				$this->aud("update `@#_member` set `money`=money+$enable_money where `uid`='{$this->userinfo['uid']}'");
				$this->ajaxReturn(array('status' => 1,'msg' => '转入成功'));
			}else{
				$model->rollback();
				$this->ajaxReturn(array('status' => 1,'msg' => '转入失败'));
			}
		}else{
			$this->ajaxReturn(array('status' => 1,'msg' => '非法操作'));
		}
	}
	
	//获取参团、创团
	private function teambuy(){
		$this->getUserinfo($this->jsonp);
		$member=$this->userinfo;
		$crodid=intval($_GET['team_order_id']);
		if (!$crodid) $this->ajaxReturn(array('status' => 0,'msg' => '订单不存在'));
		$shopinfo=$this->excq("select a.* from @#_teamgoods a left join @#_member_team_record b on b.shopid=a.id where b.id={$crodid}");
		if(!empty($shopinfo)){
			$share_title = '邀请码：['.$shopinfo['q_create_pwd'].'] '.$shopinfo['title'];
			$share_desc = $shopinfo['title2'];
			$share_link = W_WEB_PATH.'/tm/'.$shopinfo['id'].'/'._encrypt($member['uid']);
			$share_img = G_WEB_PATH.'/'.$shopinfo['thumb'];
			$find = $this->excq("select * from `@#_member_team_record` where uid='$member[uid]' and shopid='$shopinfo[id]' and `id`='{$crodid}' limit 1");
			$lottery = 'no';
			if($shopinfo['q_uid'] && $shopinfo['q_showtime'] == 'N'){
				$lottery = 'yes';
				$shopinfo['username'] = get_user_name($shopinfo['q_uid']);
				$shopinfo['q_end_time'] = microt($shopinfo['q_end_time']);
			}
			$find['goucode'] = yunma($find['goucode']);
			$find['time'] = date('Y-m-d H:i:s',$find['time']);
			$this->ajaxReturn(array('status' => 1,
					'data' => $find,
					'shopinfo' => $shopinfo,
					'lottery' => $lottery,
					'share_title' => $share_title,
					'share_desc' => $share_desc,
					'share_link' => $share_link,
					'share_img' => $share_img
			));
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '订单不存在'));
		}
	}
	
	//参加团和团开奖
	private function teamitem(){
		$itemid = isset($_GET['goods_id'])?intval($_GET['goods_id']):0;
		if (!$itemid){
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$item=$this->excq("select * from `@#_teamgoods` where `id`='".$itemid."' LIMIT 1");
		if(!$item) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		if($item['q_end_time'] && $item['q_showtime'] == 'N'){
			$this->ajaxReturn(array('status' => -1,'msg' => '已经揭晓'));
		}
		$sid = $item['sid'];
		$sid_code = $this->excq("select * from `@#_teamgoods` where `sid`='$sid' order by `id` DESC LIMIT 1,1");
		$sid_go_record=$this->excq("select * from `@#_member_team_record` where `shopid`='$sid_code[sid]' and `uid`='$sid_code[q_uid]' order by `id` DESC LIMIT 1");
		$category=$this->excq("select * from `@#_category` where `cateid` = '$item[cateid]' LIMIT 1");
		$brand=$this->excq("select * from `@#_brand` where `id`='$item[brandid]' LIMIT 1");
		$title = $item['title'];
		$syrs = $item['zongrenshu']-$item['canyurenshu'];
		$item['picarr'] = unserialize($item['picarr']);
		//参与记录
		$us = $this->excq("select * from `@#_member_team_record` where `shopid`='".$itemid."' AND `shopqishu`='".$item['qishu']."'ORDER BY id DESC LIMIT 6",2);
		$curtime=time();
		foreach ($us as $key => $value) {
			$us[$key]['mo'] = get_user_or_mobile($value['uid']);
		}
		$item['progress'] = $item['canyurenshu']/$item['zongrenshu']*100;
		$item['percent'] = '已完成'.percent($item['canyurenshu'],$item['zongrenshu']);
		$item['yurenshu'] = $item['zongrenshu']-$item['canyurenshu'];
		$lottery = 'no';
		if ($item['q_uid'] && $item['q_showtime'] == 'Y' && $item['q_end_time'] < time()){
			$lottery = 'yes';
			$item['q_end_time'] = microt($item['q_end_time']);
			$item['q_user'] = unserialize($item['q_user']);
			$gorecord = M('member_team_record')->where(array('uid' => $item['q_uid'],
					'shopid' => $item['id'],
					'goucode' => array('LIKE',"%{$item['q_user_code']}%")))->find();
			$item['gorecode_time'] = date('Y-m-d H:i:s',$gorecord['time']);
			$item['gonumber'] = $gorecord['gonumber'];
		}
		$item['lottery'] = $lottery;
		$this->ajaxReturn(array('status' => 1,
				'item' => $item,
				'us' => $us
		));
	}
	
	private function lottery_shop_team_set(){
		$gid = isset($_GET['gid']) ? abs(intval($_GET['gid'])) : $this->ajaxReturn(array('status' => 0));
		$info = $this->excq("select id,xsjx_time,q_end_time,money,q_user_code from `@#_teamgoods` where `id` ='$gid' and `q_showtime` = 'Y'");
		if(!$info){
			$this->ajaxReturn(array('status' => 0));
		}
		$this->aud("update `@#_teamgoods` SET `q_showtime` = 'N' where `id` = '$info[id]' and `q_showtime` = 'Y' and `q_uid` is not null");
		$this->ajaxReturn(array('status' => 1));
	}
	
	//团开奖揭晓结果
	private function tdataserver(){
		$itemid=intval($_GET['goods_id']);
		$item=$this->excq("select * from `@#_teamgoods` where `q_showtime`='N' and `id`='$itemid'  LIMIT 1");
		if(!$item){
			$this->ajaxReturn(array('status' => 1,'msg' => '商品不存在'));
		}
		if (!$item['q_end_time'] || empty($item['q_user_code'])) {
			$this->ajaxReturn(array('status' => -1));
		}
		$itemlist = $this->excq("select * from `@#_teamgoods` where `sid`='$item[sid]' order by `qishu` DESC",2);
		$category=$this->excq("select * from `@#_category` where `cateid` = '$item[cateid]' LIMIT 1");
		$brand=$this->excq("select * from `@#_brand` where `id` = '$item[brandid]' LIMIT 1");
	
		//购买中奖码
		$q_user = unserialize($item['q_user']);
		$q_user_code_len = strlen($item['q_user_code']);
		$q_user_code_arr = array();
		for($q_i=0;$q_i < $q_user_code_len;$q_i++){
			$q_user_code_arr[$q_i] = substr($item['q_user_code'],$q_i,1);
		}
	
		//总购买次数
		$user_shop_number = 0;
		//用户购买时间
		$user_shop_time = 0;
		//得到购买码
		$user_shop_codes = '';
		$user_shop_list = $this->excq("select * from `@#_member_team_record` where `uid`= '$item[q_uid]' and `shopid` = '$itemid' and `shopqishu` = '$item[qishu]'",2);
		foreach($user_shop_list as $user_shop_n){
			$user_shop_number += $user_shop_n['gonumber'];
			if($user_shop_n['huode']){
				$user_shop_time = $user_shop_n['time'];
				$user_shop_codes = $user_shop_n['goucode'];
			}
		}
	
		$h=abs(date("H",$item['q_end_time']));
		$i=date("i",$item['q_end_time']);
		$s=date("s",$item['q_end_time']);
		$w=substr($item['q_end_time'],11,3);
		$user_shop_time_add = $h.$i.$s.$w;
		$user_shop_fmod = fmod($user_shop_time_add*100,$item['canyurenshu']);
	
		if($item['q_content']){
			$item['q_content'] = unserialize($item['q_content']);
		}
		$item['picarr'] = unserialize($item['picarr']) ;
	
		//记录
		$itemzx=$this->excq("select * from `@#_teamgoods` where `sid`='$item[sid]' and `qishu`>'$item[qishu]' and `q_end_time` is null order by `qishu` DESC LIMIT 1");
		$gorecode=$this->excq("select * from `@#_member_team_record` where `shopid`='".$itemid."' AND `shopqishu`='".$item['qishu']."' and `uid`= '$item[q_uid]' and goucode LIKE '%{$item['q_user_code']}%' and huode!=0 LIMIT 1");
		$gorecode_count=$this->excq("select sum(gonumber) as count from `@#_member_team_record` where `shopid`='".$itemid."' AND `shopqishu`='".$item['qishu']."' and `uid`= '$item[q_uid]' and goucode LIKE '%{$item['q_user_code']}%'");
		$gorecode_count=$gorecode_count ? $gorecode_count['count'] : 0;
		$item['q_user'] = unserialize($item['q_user']);
		if (empty($item['q_user']['username'])){
			$item['q_user']['username'] = get_user_name($item['q_uid']);
		}
		$item['q_end_time'] = microt($item['q_end_time']);
		$item['user_shop_time'] = microt($user_shop_time);
		$record = $this->getbuyrecord($item['id']);
		$this->ajaxReturn(array('status' => 1,
				'item' => $item,
				'gorecode' => $gorecode,
				'record' => $record
		));
	}
	
	//ajax获取本团所有参与记录
	private function getbuyrecord($goods_id){
		if (!$goods_id){
			$this->ajaxReturn($a[0]['num'] = 0);
			exit;
		}
		//$page =  intval($this->segment(5)) ? intval($this->segment(5)) : 1; //默认1
		$member = $this->userinfo;
		$model = M('member_team_record');
		$where = array('shopid' => $goods_id);
/**
		$pageSize = 10;
		$total = $model->where($where)->count();
		$totalPage = ceil($total/$pageSize);
		if ($page == 1){
			$start = 1;
		}elseif ($page > 1){
			$start = $page;
		}
		$limit = ($start-1)*$pageSize.','.$pageSize;
 */
		$record = $model->where($where)->order('id DESC')->select();
		$userModel = M('Member');
		foreach ($record as $key => $value){
			$_temp = $userModel->where(array('uid' => $value['uid']))->field(array('email','mobile'))->find();
			$record[$key]['account'] = !empty($_temp['mobile']) ? hidtel($_temp['mobile']) : $_temp['email'];
		}
		$record[0]['num'] = count($record);
		return $record;
	}
	
	//组团商品加入购物车页面
	private function gbuy(){
		$goods_id = isset($_GET['goods_id'])?intval($_GET['goods_id']):'';
		if (!$goods_id){
			$this->ajaxReturn(array('status' => 0,'msg' => '非法访问'));
		}
		$goods = $this->excq("SELECT * FROM `@#_teamgoods` WHERE `id` = '{$goods_id}' and `q_create_uid` = '0' LIMIT 1");
		if (empty($goods)){
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$goods['picarr'] = unserialize($goods['picarr']);
		$this->ajaxReturn(array('status' => 1,'item' => $goods));
	}
	
	//创团购物车
	private function teamcartlist(){
		$cartJSON = isset($_POST['cart'])?$_POST['cart']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
		
		$shoplist=array();
		if($shopids!=NULL){
			$shoparr=$this->model->query("SELECT * FROM `".C('DB_PREFIX')."teamgoods` where `id` in($shopids)",array("key"=>"id"));
		}
		if(!empty($shoparr)){
			foreach($shoparr as $key=>$val){
				if($val['q_end_time']=='' || $val['q_end_time']==NULL){
					$shoplist[$val['id']]=$val;
					$Mcartlist[$val['id']]['num']=$Mcartlist[$val['id']]['num'];
					$Mcartlist[$val['id']]['shenyu']=$val['shenyurenshu'];
					$Mcartlist[$val['id']]['money']=$val['yunjiage'];
				}
			}
		}
		$MoenyCount=0;
		$_temp = array();
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					$shoplist[$key]['group_name'] = $val['groupname'];
					$_temp[$key] = array(
							"shenyu" => $shoplist[$key]['cart_shenyu'],
							"num" => $val['num'],
							"money" => $shoplist[$key]['yunjiage']
					);
				}
			}
		}
		
		$shop=0;
		if(!empty($shoplist)){
			$shop=1;
		}
		$MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
		$this->ajaxReturn(array('shop' => $shop,'shoplist' => $shoplist,'cartinfo' => $_temp,'MoenyCount' => $MoenyCount),'json');
	}
	
	//组团结算
	private function team_payment(){
		$this->getUserinfo();
		$cartJSON = isset($_POST['json'])?$_POST['json']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
		$shoplist=array();
		if($shopids!=NULL){
			$arr = explode(',', $shopids);
			$shoplist=$this->excq("SELECT * FROM `@#_teamgoods` where `id` in($shopids)",3,$arr);
		}
		$MoenyCount=0;
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					$ten_per = floor($shoplist[$key]['zongrenshu']/1) > 0 ? floor($shoplist[$key]['zongrenshu']/1) : 1;
					$max = $ten_per > $shoplist[$key]['cart_shenyu'] ? $shoplist[$key]['cart_shenyu'] : $ten_per;
					if($val['num'] > $max){
						//_messagemobile($shoplist[$key]['title']."购买数量不能大于".$max,WEB_PATH.'/mobile/cart/cartlist');
					}
				}
			}
			$shopnum=0;  //表示有商品
		}else{
			// _setcookie('Cartlist',NULL);
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
	
		// 总支付价格
		$MoenyCount = substr( sprintf ( "%.3f", $MoenyCount), 0, - 1 );
		// 会员余额
		$Money = $this->userinfo['money'];
		// 商品数量
		$shoplen = count($shoplist);	
		$paylist = $this->excq("SELECT * FROM `@#_pay` where `pay_start` = '1' AND pay_mobile = 1",2);
		$alipay_key = require_once APP_CORE.'/config/key.inc.php';
		foreach ($paylist as $key => $value){
			$pay_key = unserialize($value['pay_key']);
			if($value['pay_class'] == 'wapalipay'){
				$paylist[$key]['pay_partner'] = $pay_key['id']['val'];
				$paylist[$key]['pay_key'] = $pay_key['key']['val'];
				$paylist[$key]['pay_account'] = $pay_key['user']['val'];
				$paylist[$key]['public_key'] = $alipay_key['alipay']['public_key'];
				$paylist[$key]['private_key'] = $alipay_key['alipay']['private_key'];
			}elseif ($value['pay_class'] == 'wxpay_web'){
				$paylist[$key]['pay_partner'] = $pay_key['APPID']['val'];
				$paylist[$key]['pay_key'] = $pay_key['KEY']['val'];
				$paylist[$key]['pay_account'] = $pay_key['MCHID']['val'];
			}
		}
		$payhtml = '';
		foreach ($paylist as $key => $value) {
			$payhtml .= '<li class="gray9 select_pay" urm="'.$value['pay_id'].'"><i><s></s>';
			$checked = '';
			$css = "";
			if($value['pay_class'] == 'wapalipay'){
				$checked = 'checked="checked"';
				$css = 'class="selectedP"';
			}
			$payhtml .= '<input id="'.$value['pay_id'].'" item="'.$value['pay_class'].'" class="regular-radio" '.$checked.' type="radio" value="'.$value['pay_id'].'" name="account" id="'.$value['pay_class'].'">';
			$payhtml .= '<label for="'.$value['pay_id'].' '.$css.'"></label></i>'.$value['pay_name'].'</li>';
		}
	
		$this->ajaxReturn(array('status' => 1,
				'money' => $Money,
				'hidPoints' => $this->userinfo['score'],
				'count'=> $shoplen,
				'payapi' => $paylist,
				'paylist' => $payhtml,
				'pay_type' => $Money>=$MoenyCount?'ok':'error',
				'shoplist' => $shoplist,
				'MoenyCount' => $MoenyCount),'json');
	}
	
	//组团余额支付
	private function team_paysubmit() {
		$this->is_check_postCart();
		$checkpay = isset($_POST['checkpay'])?$_POST['checkpay']:''; // 获取支付方式 fufen money bank
		$banktype = isset($_POST['banktype'])?$_POST['banktype']:''; // 获取选择的银行 CMBCHINA ICBC CCB
		$money = isset($_POST['money'])?$_POST['money']:''; // 获取需支付金额
		$fufen = isset($_POST['score'])?$_POST['score']:''; // 获取福分
		$isBag = isset($_POST['bag'])?$_POST['bag']:'a';
		//$submitcode1 = $this->segment (8); // 获取SESSION 做防止重复提交
		$uid = $this->userinfo ['uid'];
		$zhifutype = $this->excq("select * from `@#_pay` where `pay_class` = 'alipay'");
		if (!$zhifutype) {
			$this->ajaxReturn(array('status' => 0,'msg' => '请使用微支付或支付宝'),'json');
		}
		$pay_checkbox = false; //钱包支付
		$pay_type_bank = false; //银行卡支付
		$pay_type_id = false;   //获取平台支付类型，支付宝，微信支付...
		if ($checkpay == 'money') {
			$pay_checkbox = true;
		}
		//不是银行
		if ($banktype != 'nobank') {
			$pay_type_id = $banktype; //支付类型的id
		}
		if (! empty ($zhifutype)) {
			$pay_type_bank = $zhifutype['pay_class'];
		}
		if (!$pay_type_id) {
			if ($checkpay != 'fufen' && $checkpay != 'money'){
				$this->ajaxReturn(array('status' => 0,'msg' => '请使用微支付或支付宝2'),'json');
			}
		}
	
		$pay = new pay();// 购买商品
		$pay->pay_type_str = $isBag;
		$pay->uid = $this->userinfo['uid'];
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$pay->fufen = $checkpay == 'fufen'?$fufen:0;
		$pay->pay_type_bank = $pay_type_bank;
		//提交订单时间，实时检测商品
		$exec_pay = $pay->init($uid,$pay_type_id,'team_record');
		if ($exec_pay === true) {
			$_temp = array();
			foreach ($pay->teamCreateInfo as $key => $value){
				$_temp = array(
					'goods_id' => $key,
					'title' => _htmtocode2($value['title']),
					'title2' => _htmtocode2($value['title2']),
					'description' => _htmtocode2($value['description']),
					'thumb' => $value['thumb'],
					'q_group_name' => $value['q_group_name'],
					'q_create_pwd' => $value['q_create_pwd']
				);
			}
			$share_link = W_WEB_PATH.'/tm/'.$_temp['goods_id'].'/'._encrypt($this->userinfo['uid']);
			$share_title = $_temp['title'];
			$share_desc = $_temp['description']?$_temp['description']:$_temp['title2'];
			$share_img = $_temp['thumb'];
			$goods_id = $_temp['goods_id'];
			// 成功
			$this->ajaxReturn(array('status' => 1,
					'share_link' => $share_link,
					'share_title' => $share_title,
					'share_desc' => $share_desc,
					'share_img' => $share_img,
					'share_goods_id' => $goods_id,
					'group_name' =>  $_temp['q_group_name'],
					'create_pwd' => $_temp['q_create_pwd'],
					'msg' => '组团成功'),'json');
		}elseif ($exec_pay === false){
			// 失败
			$this->ajaxReturn(array('status' => 0,'msg' => '订单添加失败'),'json');
		}else {
			$this->ajaxReturn(array('status' => 0,'msg' => $exec_pay),'json');
		}
	}
	
	//代理提现记录
	private function agentcashoutrecord(){
		$this->getUserinfo($this->jsonp);
		$member=$this->userinfo;
		$uid = $member['uid'];
		if (isset($_GET['detail'])){
			$id = intval($_GET['id']);
			if (!$id){
				$this->ajaxReturn(array('status' => 0));
			}
			$data = M('member_agent_cashout')->where(array('id' => $id,'uid' => $this->userinfo['uid']))->find();
			$_temp = array();
			foreach ($data as $key => $value) {
				switch ($key){
					case 'username':
						$_temp[] = "开户人：".$value;
						break;
					case 'bankname':
						$_temp[] = "开户银行：".$value;
						break;
					case 'branch':
						$_temp[] = "开户支行：".$value;
						break;
					case 'money':
						$_temp[] = "提现金额：".$value.'元';
						break;
					case 'banknumber':
						$_temp[] = "银行卡号：".$value;
						break;
					case 'linkphone':
						$_temp[] = "联系电话：".$value;
						break;
					case 'auditstatus':
						$status = $value==1 ?'已通过':'未审核';
						$_temp[] = "是否审核：".$status;
						break;
					case 'time':
						$_temp[] = "提现时间：".date('Y-m-d H:i:s',$value);
						break;
				}
			}
			$this->ajaxReturn(array('status' => 1,'data' => $_temp));
		}		
		$recordarr=$this->excq("select * from  `@#_member_agent_cashout`  where `uid`='$uid' ORDER BY `time` DESC limit 0,100",2);
		foreach ($recordarr as $key => $value){
			$recordarr[$key]['time'] = date('Y-m-d H:i:s',$value['time']);
		}
		$this->ajaxReturn(array('status' => 1,'data' => $recordarr));
	}
	
	//申请代理商
	private function applyfor(){
		$this->getUserinfo($this->jsonp);
		if ($this->userinfo['type'] == 1 && $this->userinfo['is_check']==2){
			$this->ajaxReturn(array('status' => 99,'msg' => '您已经是代理商'));
		}elseif($this->userinfo['type']==1 && $this->userinfo['is_check']==1){
			$this->ajaxReturn(array('status' => 99,'msg' => '您的申请正在审核中'));
		}
		$this->ajaxReturn(array('status' => 1,
				'money' => $this->userinfo['money'],
				'tel' => getConfig('cell'),
				'agent_price' => getConfig('agent_price'),
		));
	}
	
	//申请发送验证码
	private function aplysendcode(){
		$this->sendcode(2);
	}
	
	//代理提交申请
	private function postapplyfor(){
		if (isset($_POST['submit'])){
			$this->getUserinfo();
			$member=$this->userinfo;
			if (empty($member)){
				$this->ajaxReturn(array('status' => 0, 'msg' => '请登录用户'),$this->json);
				
			}
			if ($member['is_pay'] == 1 || $member['type'] == 1){
				$this->ajaxReturn(array('status' => 0, 'msg' => '您的申请正在审核中...'),$this->json);
				
			}
	
			$activeModel = M('sms_activity_code');
			$Now = strtotime(date('Y-m-d').' 00:00:00');
			$active_code = $activeModel->where(array('time' => array('GT',$Now),'type' => 2,'uid' => $member['uid']))->order('time DESC')->find();
			if ($active_code['active_time'] < NOW_TIME-$active_code['time']){
				$this->ajaxReturn(array('status' => 0, 'msg' => '动态码已超时'),$this->json);
				
			}elseif ($active_code['code'] != $_POST['active_code']){
				$this->ajaxReturn(array('status' => 0, 'msg' => '动态码错误'),$this->json);
				
			}elseif (empty($active_code) || $active_code['status'] == 1){
				$this->ajaxReturn(array('status' => 0, 'msg' => '动态码已失效'),$this->json);
				
			}
	
			$check_code = 'A'.time().substr(microtime(),2,6).rand(0,9);
	
			$is = M('agent_pay')->where(array('uid' => $member['uid'],'code' => $member['check_code']))->find();
			if (empty($is)){
				$price = M('config')->where(array('name' => 'agent_price'))->getField('value');
				$data = array(
						'truename' => I('post.truename'),
						'province' => I('post.province'),
						'city' => I('post.city'),
						'area' => I('post.area'),
						'is_pay' => 0,
						'is_check' => 1,
						'check_code' => $check_code,
						'pay_price' => $price,
						'join_time' => NOW_TIME,
						'payment' => I('post.payment')
				);
				if (M('Member')->where(array('uid' => $member['uid']))->save($data)){
					$activeModel->where(array('id' => $active_code['id']))->setField('status',1);
					$activeModel->where(array('mobile' => I('post.mobile')))->setField('status',1);
					$order = array(
							'uid' => $member['uid'],
							'code' => $check_code,
							'price' => $data['pay_price'],
							'status' => 0,
							'time' => NOW_TIME
					);
					if (M('agent_pay')->data($order)->add()){
						$this->ajaxReturn(array('status' => 1, 'msg' => '提交成功，正在跳转支付'),$this->json);
					}else{
						$this->ajaxReturn(array('status' => 0, 'msg' => '提交失败'),$this->json);
					}
				}else{
					$this->ajaxReturn(array('status' => 0, 'msg' => '提交失败'),$this->json);
				}
			}elseif ($is['status'] == 0){
				$this->ajaxReturn(array('status' => 1,'o' => $is['code'], 'msg' => '您已提交过申请，正在跳转支付'),$this->json);
			}
		}else{
			$this->ajaxReturn(array('status' => 0, 'msg' => '非法操作'),$this->json);
		}
	}
	
	/**
	 * 提交申请成功，跳转支付
	 */
	private function applypay(){
		$this->getUserinfo($this->jsonp);
		if (empty($this->userinfo)) $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'));
		if ($this->userinfo['is_pay'] && $this->userinfo['is_check'] == 2){
			$this->ajaxReturn(array('status' => 0,'msg' => '您已经是代理商'));
		}
		$order = M('agent_pay')->where(array('uid' => $this->userinfo['uid'],'code' => $this->userinfo['check_code']))->find();
		if (empty($order)) $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'));
		if($this->userinfo['money'] >= $order['price']){
			$update = array(
					'is_pay' => 1,
					'type' => 1,
					'level_id' => 0,
					'is_check' => 1,
					'check_code' => '',
					'money'	=> $this->userinfo['money']-$order['price']
			);
			if(M('Member')->where(array('uid' => $this->userinfo['uid']))->save($update)){
				$member_account = array(
						'uid' => $this->userinfo['uid'],
						'type' => -1,
						'pay' => '账户',
						'content' => '申请代理商权',
						'money' => $order['price'],
						'time' => NOW_TIME
				);
				$qu1 = M('member_account')->add($member_account);
				$qu2 = M('agent_pay')->where(array('uid' => $this->userinfo['uid'],'code' => $this->userinfo['check_code']))->setField('status',1);
				if ($qu1 && $qu2){
					$mobile = trim(getConfig('agent_notice'));
					if ($this->userinfo['mobile']){
						//$content = '会员'.$this->userinfo['mobile'].'在'.getConfig('web_name').'系统中申请代理商，现已付款'.$order['price'].'元，请尽快审核！【'.getConfig('sms_sign').'】';
						$content = $this->userinfo['mobile'];
					}elseif ($this->userinfo['email']){
						//$content = '会员'.$this->userinfo['email'].'在'.getConfig('web_name').'系统中申请代理商，现已付款'.$order['price'].'元，请尽快审核！【'.getConfig('sms_sign').'】';
						$content = $this->userinfo['email'];
					}else{
						//$content = '会员UID为'.$this->userinfo['uid'].'在'.getConfig('web_name').'系统中申请代理商，现已付款'.$order['price'].'元，请尽快审核！【'.getConfig('sms_sign').'】';
						$content = 'UID为'.$this->userinfo['uid'];
					}
					//_renhu_sendmobile($mobile, $content);
					send_mobile_sms($mobile,array($content,$order['price']),APPLYFOR_NOTICE_TPL);
					$this->ajaxReturn(array('status' => 1,'msg' => '您的提交己成功，工作人员将会在24小时内审核通过！'));
				}else{
					$this->ajaxReturn(array('status' => 0,'msg' => '支付失败'));
				}
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '支付失败'));
			}
		}else{
			$this->ajaxReturn(array('status' => 3,'msg' => '您的账户余额不足请充值'));
		}
	}
	
	//获取商品分类
	private function category(){
		$type = I('type','');
		if ($type=='onfree'){
			$where = array('model' => 1,'name' => array('NEQ','免费抢购'));
		}else{
			$where = array('model' => 1);
		}
	 	$list = M('Category')->where($where)
		->field(array('cateid','name','catdir','order'))->order('`order` asc')->select();
	 	$html = '';
	 	foreach ($list as $key => $value){
	 		if ($value['name'] == '免费抢购') continue;
	 		$html .= '<li><a href="javascript:;" id="'.$value['cateid'].'">';
	 		$html .= '<i class="ricon iconfont iconline-arrow-right"></i>';
	 		$html .= '<div class="text">'.trim($value['name']).'</div>';
	 		$html .= '</a></li>';
	 	}
		$this->ajaxReturn(array('count' => 46*count($list)+76,'html' => $html));
	}
	
	//ajax获取组团商品
	private function grouplistajax(){
		$cate_band = isset($_GET['show'])?intval($_GET['show']):''; //分类
		$select = isset($_GET['sort'])?$_GET['sort']:''; //排序
		$p = isset($_GET['page'])?$_GET['page']:1; //分页数
		if(!$select){
			$select = '10';
		}
		$fen1 = 0;
		if($cate_band){
			$fen1 = $cate_band;
			$cate_band = 'list';
		}
		$sun_id_str = "'".$fen1."'";
		if($fen1){
			$sun_cate = $this->excq("SELECT cateid from `@#_category` where `parentid` = '$fen1'",2);
			foreach($sun_cate as $v){
				$sun_id_str .= ","."'".$v['cateid']."'";
			}
		}
	
		if(empty($fen1)){
			$brand= $this->excq("select * from `@#_brand` where 1 order by `order` DESC",2);
			$daohang = '所有分类';
		}else{
			$brand=$this->excq("select * from `@#_brand` where `cateid` in ($sun_id_str) order by `order` DESC",2);
			$daohang=$this->excq("select * from `@#_category` where `cateid` = '$fen1' order by `order` DESC");
			$daohang = $daohang['name'];
		}
		
		$category=$this->excq("select * from `@#_category` where `model` = '1'",2);
	
		//分页
		$end=10;
		$star=($p-1)*$end;
	
		$select_w = '';
		if($select == 10){
			$select_w = 'order by `shenyurenshu` ASC';
		}
		if($select == 20){
			$select_w = "and `renqi` = '1'";
		}
		if($select == 30){
			$select_w = 'order by `shenyurenshu` ASC';
		}
		if($select == 40){
			$select_w = 'order by `time` DESC';
		}
		if($select == 50){
			$select_w = 'order by `money` DESC';
		}
		if($select == 60){
			$select_w = 'order by `money` ASC';
		}
	
		if($fen1){
			$count=$this->excq("select * from `@#_teamgoods` where `q_create_uid` = '0' and `type` = 2 and `q_uid` is null and `cateid` in ($sun_id_str) $select_w",2);
		}else{
			$count=$this->excq("select * from `@#_teamgoods` where `q_create_uid` = '0' and `type` = 2 and `q_uid` is null $select_w",2);
		}
		if($fen1){
			$shoplist=$this->excq("select * from `@#_teamgoods` where `q_create_uid` = '0' and `type` = 2 and `q_uid` is null and `cateid` in ($sun_id_str) $select_w",2);
		}else{
			$shoplist=$this->excq("select * from `@#_teamgoods` where `q_create_uid` = '0' and `type` = 2 and `q_uid` is null $select_w",2);
		}
		$max_renqi_qishu = 1;
		$max_renqi_qishu_id = 1;
		
		$this_time = time();
		if(count($shoplist) > 1){
			if($shoplist[0]['time'] > $this_time - 86400*3)
				$shoplist[0]['t_new_goods'] = 1;
		}
		$pagex=ceil(count($count)/$end);
		if($p<=$pagex){
			$shoplist[0]['page']=$p+1;
		}
		if($pagex>0){
			$shoplist[0]['sum']=$pagex;
		}else if($pagex==0){
			$shoplist[0]['sum']=$pagex;
		}
		
		$this->ajaxReturn($shoplist);
	}
	
	//重置登录密码
	private function setpassword(){
		$this->getUserinfo();
		$member=$this->userinfo;
		$Now = strtotime(date('Y-m-d').' 00:00:00');
		$active_code = M('sms_activity_code')->where(array('time' => array('GT',$Now),'type' => 1,'uid' => $member['uid']))->order('time DESC')->find();
		if ($active_code['active_time'] < NOW_TIME-$active_code['time']){
			$this->ajaxReturn(array('status' => 0, 'msg' => '动态码已超时'),'json');
		}elseif ($active_code['code'] != $_POST['active_code']){
			$this->ajaxReturn(array('status' => 0, 'msg' => '动态码错误'),'json');
		}elseif (empty($active_code) || $active_code['status'] == 1){
			$this->ajaxReturn(array('status' => 0, 'msg' => '动态码已失效'),'json');
		}
		
		$password=isset($_POST['password']) ? $_POST['password'] : "";
		$userpassword=isset($_POST['userpassword']) ? $_POST['userpassword'] : "";
		$userpassword2=isset($_POST['userpassword2']) ? $_POST['userpassword2'] : "";
		if($password==null or $userpassword==null or $userpassword2==null){
			$this->ajaxReturn(array('status' => 0, 'msg' => '密码不能为空'),'json');
		}
		if(mb_strlen($_POST['password'],'utf-8')<6){
			$this->ajaxReturn(array('status' => 0, 'msg' => '密码不能小于6位'),'json');
		}
		if($_POST['userpassword']!=$_POST['userpassword2']){
			$this->ajaxReturn(array('status' => 0, 'msg' => '确定密码不一致'),'json');
		}
		
		$password=md5($password);
		$userpassword=md5($userpassword);
		if($member['password']!=$password){
			$this->ajaxReturn(array('status' => 0, 'msg' => '原密码错误,请重新输入!'),'json');
		}else{
			M('member')->where(array('uid' => $member['uid']))->setField('password',$userpassword);
			M('sms_activity_code')->where(array('uid' => $member['uid']))->setField('status',1);
			$this->ajaxReturn(array('status' => 1, 'msg' => '密码修改成功,请重新登录!'),'json');
		}
	}
	
	//首页倒计时完毕获得商品信息
	private function get_shop_info(){
		$goods_id = intval($_GET['goods_id']);
		if ($goods_id){
			$model = M('shoplist');
			$model->where(array('id' => $goods_id))->setField('q_showtime','N');
			$data = $model->where(array('id' => $goods_id))->find();
			$data['username'] = get_user_name($data['q_uid']);
			$data['status']  =1;
			$this->ajaxReturn($data);
		}else{
			$this->ajaxReturn(array("status" => 0));
		}
	}
	
	//大转盘
	private function turntable(){
		$LotteryList = $this->excq("SELECT * FROM `@#_activity_lottery` ORDER BY id DESC LIMIT 100",2);
		$noScroller = true;
		foreach ($LotteryList as $key => $value) {
			$LotteryList[$key]['username'] = _strcut(userid($value['uid'],'username'),11,'***');
		}
		$this->ajaxReturn(array('status' => 1,'data' => $LotteryList));
		
	}
	
	private function _return($ok, $desc, $round = 0, $left=0) {
		$data = array();
		$data['ok'] = $ok;
		$data['desc'] = $desc;
		$data['round'] = $round;
		$data['left'] = $left;
		$this->ajaxReturn($data,'json');
	}
	
	public function submit() {
		$this->prize[] = array('七等奖', '1元红包', 1,  array(800,1000) );
		$this->prize[] = array('六等奖', '2元红包', 2, array(180,1000) );
		$this->prize[] = array('五等奖', '3元红包', 3, array(10,1000) );
		$this->prize[] = array('四等奖', '4元红包', 4, array(7,1000) );
		$this->prize[] = array('三等奖', '6元红包', 6, array(2,1000) );
		$this->prize[] = array('二等奖', '8元红包', 8, array(1,1000) );
		$this->prize[] = array('一等奖', '10元红包', 10, array(0,0) );
		$uid = intval(_encrypt($_POST['uid'],'DECODE'));
		if (!$uid || !($this->userinfo = M('member')->where(array('uid' => $uid))->find())) {
			
			
			$this->_return(false,'您还没有登陆，无法参与抽奖哦');
		} else if ($this->userinfo['score'] <= 1000 ) {
			$this->_return(false,'抱歉，您的抽奖次数用完了。');
		}
	
		$p = $this->probability();
		if ( $p == -1 ) {
			$this->_return(true, '哎呀，姿势不对吧，竟然没中奖！', -1);
		} else {
			list($title,$desc,$money) = $this->prize[$p];
			$round = $this->round($p);
			$left = $this->userinfo['score'] -1000;

			$this->aud("UPDATE `@#_member` SET score = score - 1000,`money` = `money` + $money where (`uid` = '".$this->userinfo['uid']."')");
			$this->aud("INSERT INTO `@#_activity_lottery`(uid,prize,money,time,title,`desc`)VALUES('".$this->userinfo['uid']."','$p','$money','".time()."','{$title}','{$desc}')");
			$this->aud("INSERT INTO `@#_member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('".$this->userinfo['uid']."', '1', '账户', '大转盘抽奖[{$title}]红包', '$money', '".time()."')");
			
			$this->_return(true, '恭喜您抽中['.$title.']'.$desc."\n红包已自动充值到您的余额内了。", $round, $left);
		}
	}
	
	# 获取范围
	private function round($p) {
		$width = 360 / 7;
		$a = $p * $width;
		$b = $a + $width;
		return mt_rand($a + 10 ,$b - 10);
	}
	
	# 随机一个概率出来
	private function probability() {
	//return rand(0,6);
		$probability_all = array(0,0);
		foreach($this->prize as $i=>$val) {
		list($title,$desc,$money,$probability) = $val;
		$probability_all[0] += $probability[0];
		$probability_all[1] += $probability[1];
		}
		if ( empty($this->prize) ) {
		return -1;
	}
	
	
	$probability_all[1] = intval($probability_all[1] / count($this->prize));
	
	$yes = mt_rand(1,$probability_all[1]);
	
	$prize = -1;
	if ( $probability_all[0] <= 0 || $probability_all[1] <= 0 || $yes > $probability_all[0] ) {
	} else {
	$list = array();
	$add = 0;
	$total = 0;
	foreach($this->prize as $i=>$val) {
	list($title,$desc,$money,$probability) = $val;
		if ( $probability[0] <= 0 ) {
		continue;
	}
	$total = $add += $probability[0];
	$list[$add] = $i;
	}

	$yes = mt_rand(1,$total);
	foreach ($list as $k => $v) {
	if ( $yes <= $k ) {
	$prize = $v;
	break;
	}
	}
	}
	return $prize;
	}
	
	//当前商品是否被抢光
	private function addshopcart(){
		$goods_id = intval($_GET['goods_id']);
		if(!$goods_id){
			$this->ajaxReturn(array('code' => 1));
		}
		$shenyurenshu = M('shoplist')->where(array('id' => $goods_id))->getField('shenyurenshu');
		if ($shenyurenshu <= 0){
			$this->ajaxReturn(array('code' => 1));
		}else{
			$this->ajaxReturn(array('code' => 0));
		}
	}
	
	//当前商品是否有效
	private function checkshopcart(){
		$goods_id = intval($_GET['goods_id']);
		if(!$goods_id){
			$this->ajaxReturn(array('code' => 1));
		}
		$zongrenshu = M('jf_shoplist')->where(array('id' => $goods_id))->getField('zongrenshu');
		if ($zongrenshu <= 0){
			$this->ajaxReturn(array('code' => 1));
		}else{
			$this->ajaxReturn(array('code' => 0));
		}
	}
	
	//当前商品是否被抢光
	private function join_addshopcart(){
		$goods_id = intval($_GET['goods_id']);
		if(!$goods_id){
			$this->ajaxReturn(array('code' => 1));
		}
		$shenyurenshu = M('teamgoods')->where(array('id' => $goods_id))->getField('shenyurenshu');
		if ($shenyurenshu <= 0){
			$this->ajaxReturn(array('code' => 1));
		}else{
			$this->ajaxReturn(array('code' => 0));
		}
	}
	
	//当前商品是否被抢光
	private function f_addshopcart(){
		$goods_id = intval($_GET['goods_id']);
		if(!$goods_id){
			$this->ajaxReturn(array('code' => 1));
		}
		$goods = M('shoplist')->where(array('id' => $goods_id))->find();
		if ($goods['shenyurenshu'] <= 0){
			$this->ajaxReturn(array('code' => 1));
		}else{
			//0新手夺宝 1逆袭夺宝 2 特惠夺宝
			if ($goods['freetype'] == 0){
				$time = time()-$this->userinfo['time'];
				if ($time < intval($goods['registerDay'])*3600*24){
					$this->ajaxReturn(array('code' => 1,'msg' => '新手夺宝注册满'.$goods['registerDay'].'天才能购买'));
				}
			}
			if ($goods['freetype'] == 1){
				$ids = M('shoplist')->where(array('sid' => $goods['sid']))->getField('id');
				$shopinfo = M('Member_go_record')->where(array('uid' => $this->userinfo['uid'],'huode' => array('NEQ','0'),'shopid' => array('IN',$ids)))->select();
				if (!empty($shopinfo)){
					$this->ajaxReturn(array('code' => 1,'msg' => '您已经中过奖不能购买'));
				}
			}
			$this->ajaxReturn(array('code' => 0));
		}
	}
	
	//创团当前商品是否被抢光
	private function team_addshopcart(){
		$goods_id = intval($_GET['goods_id']);
		if(!$goods_id){
			$this->ajaxReturn(array('code' => 1));
		}
		$shenyurenshu = M('teamgoods')->where(array('id' => $goods_id))->getField('shenyurenshu');
		if ($shenyurenshu <= 0){
			$this->ajaxReturn(array('code' => 1));
		}else{
			$this->ajaxReturn(array('code' => 0));
		}
	}
	
	//首页倒计时
	private function show_get_lottery(){
		$str = $_GET['gids'];
		$str = substr($str, 0,-1);
		$arr = '';
		if (!empty($str)){
			$arr = explode('_', $str);
		}
		$where = array('q_showtime' => 'Y','q_end_time' => array('exp','is not null'));
		if (!empty($arr)){
			$ids = implode(',', $arr);
			$where['id'] = array('NOT IN',$ids);
		}
		//即将揭晓商品
		$data = M('shoplist')->where($where)->find();
		if (empty($data)){
			$data["status"] = 0;
		}else{
			$data['username'] = get_user_name($data['q_uid']);
			$data["status"] = 1;
			$data["q_end_time"] = intval($data['q_end_time']-time());
		}
		$this->ajaxReturn($data);
	}
	
	//首页即将揭晓
	private function homeget(){
		$this->ajaxReturn($this->__homeget());
	}
	private function __homeget(){
		$sql = "select $this->field from `".C('DB_PREFIX')."shoplist` where `q_user_code` is not null and `q_showtime`= 'N' and `isFree`=0 ORDER BY `q_end_time` DESC limit 4";
		$data = $this->model->query($sql);
		if (!empty($data)){
			foreach ($data as $key => $value) {
				$data[$key]['username'] = get_user_name($value['q_uid']);
			}
		}
		return array('status' => 1,'data' => $data);
	}
	
	//上传头像图片
	private function uplaodface(){
		$this->getUserinfo();
		$uid = $this->uid;
		if (!$uid) $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'),'json');
		$userModel = M('member');
		$member = $userModel->where(array('uid' => $uid))->find();
		if (empty($member))  $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'),'json');
		$upload = new UploadFile();
		$upload->maxSize = -1;
		$upload->supportMulti = false;
		//$upload->allowExts = array('jpg','png','jpeg','gif');
		//$upload->allowTypes = array('image/jpeg');
		$upload->thumb = true;
		$upload->thumbMaxWidth = '70';
		$upload->thumbMaxHeight = '70';
		$upload->autoSub = true;
		$upload->subType = 'date';
		$upload->dateFormat = 'Ymd';
		$upload->savePath = '../uploads/touimg/';
		if ($upload->upload()){
			$info = $upload->getUploadFileInfo();
			/*
			$path = $info[0]['savename'];
			$arr = explode('/', $path);
			$filename = $arr[0];
			$img = 'thumb_'.$arr[1];
			$path2 = $filename.'/'.$img;
			*/
			
			$arr = explode('/', $info[0]['savename']);
			$newFilename = $arr[1].'jpg';
			$path = $arr[0].'/'.$newFilename;
			$path2 = $path;
			rename($upload->savePath.$info[0]['savename'], $upload->savePath.$path);
			
			$userModel->where(array('uid' => $member['uid']))->setField('img','touimg/'.$path);
			//$this->ajaxReturn(array('status' => 1,'path' => substr($upload->savePath,2).$path2,'path2' => 'touimg/'.$path2),'json');
			$this->ajaxReturn(array('status' => 1,'path' => '/'.$upload->savePath.$path2,'path2' => 'touimg/'.$path2),'json');
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => $upload->getErrorMsg()),'json');
		}
	}
	
	//设置昵称
	private function set_nickname(){
		$this->getUserinfo();
		$uid = $this->uid;
		if (!$uid) $this->ajaxReturn(array('status'=> 0,'msg' => '非法操作'),'json');
		$nickname = I('post.param');
		$enabled = M('caches')->where(array('key' => 'member_name_key'))->getField('value');
		$arr = explode(',', $enabled);
		if (in_array($nickname, $arr)){
			$this->ajaxReturn(array('status' => 0,'msg' => '昵称不合法'));
		}
		
		if(empty($nickname) || mb_strlen($nickname,'utf-8') > 20 || mb_strlen($nickname,'utf-8') < 2) {
			$this->ajaxReturn(array('status' => 0,'msg' => '昵称长度2~20位'),'json');
		}
		if(M('member')->where(array('uid' => $uid))->setField('username',$nickname)){
			$this->ajaxReturn(array('status' => 1,'msg' => '保存成功'),'json');
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '保存失败'),'json');
		}
	}
	
	//设置手机号码
	private function set_mobile(){
		$this->getUserinfo();
		$uid = $this->uid;
		if (!$uid) $this->ajaxReturn(array('status'=> 0,'msg' => '非法操作'),'json');
		$mobile = I('post.param');
		$in = M('member')->where(array('mobile' => $mobile,'uid' => array('NEQ',$uid)))->find();
		if($in || !_checkmobile($mobile)){
			$this->ajaxReturn(array('status' => 0,'msg' => '手机号已被使用或格式不正确'),'json');
		}
		if(M('member')->where(array('uid' => $uid))->setField('mobile',$mobile)){
			$this->ajaxReturn(array('status' => 1,'msg' => '保存成功'),'json');
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '保存失败'),'json');
		}
	}
	
	//设置邮箱
	private function set_email(){
		$this->getUserinfo();
		$uid = $this->uid;
		if (!$uid) $this->ajaxReturn(array('status'=> 0,'msg' => '非法操作'),'json');
		$email = I('post.param');
		$in = M('member')->where(array('email' => $email,'uid' => array('NEQ',$uid)))->find();
		if($in || !_checkemail($email)){
			$this->ajaxReturn(array('status' => 0,'msg' => '邮箱已被使用或格式不正确'),'json');
		}
		if(M('member')->where(array('uid' => $uid))->setField('email',$email)){
			$this->ajaxReturn(array('status' => 1,'msg' => '保存成功'),'json');
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '保存失败'),'json');
		}
	}
	
	//编辑个性签名
	private function set_signmin(){
		$this->getUserinfo();
		$uid = $this->uid;
		if (!$uid) $this->ajaxReturn(array('status'=> 0,'msg' => '非法操作'),'json');
		$signmin = I('post.param');
		if(empty($signmin) || mb_strlen($signmin,'utf-8') > 80 || mb_strlen($signmin,'utf-8') < 2) {
			$this->ajaxReturn(array('status' => 0,'msg' => '个性签名内容长度2～80之间'),'json');
		}
		if(M('member')->where(array('uid' => $uid))->setField('qianming',$signmin)){
			$this->ajaxReturn(array('status' => 1,'msg' => '保存成功'),'json');
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '保存失败'),'json');
		}
	}
	
	private function getSlides(){
		$sql="select * from `".C('DB_PREFIX')."wap` order by id desc";
		$SlideList=$this->model->query($sql);
		if(empty($SlideList)){
			$slides['state']=1;
		}else{
			$slides['state']=0;
			foreach($SlideList as $key=>$val){
				//$shopid = preg_replace('[^0-9]', '', $val['link']);
				//$slides['listItems'][$key]['alt']=$val['color'];
				//$shopid = 0;
				//if (preg_match('/[\d]+/', $val['link'],$arr)){
				//	@$shopid = $arr[0];
				//}
				//$slides['listItems'][$key]['url']= W_WEB_PATH."/mobile/mobile/item/".$shopid;
				$slides['listItems'][$key]['url']= $val['link'];
				$slides['listItems'][$key]['src']= ADVER_WEB_PATH."/uploads/".$val['img'];
				//$slides['listItems'][$key]['width']='614PX';
				//$slides['listItems'][$key]['height']='110PX';
			}
		}
		return $slides;
	}
	
	//轮播器
	private function slides(){
		$slides = $this->getSlides();
		$this->ajaxReturn($slides);
	}
	
	//修改密码头发验证码
	private function setpwdsendcode(){
		$this->sendcode(1);
	}
	
	private function getLimit($total,$page=1,$pageSize=15){
		if (empty($pageSize)) $pageSize = 15;
		$totalPage = ceil($total/$pageSize);
		if ($page > 1){
			$start = $page;
			if ($totalPage <= $page){
				$start = $totalPage;
			}
		}else{
			$start = 1;
		}
		$limit = 'limit '.($start-1)*$pageSize.','.$pageSize;
		return array('limit' => $limit,'totalPage' => $totalPage);
	}
	
	private function userfufen(){
		$this->getUserinfo($this->jsonp);
		$member = $this->userinfo;
		$uid = $member['uid'];
		$page = I('page',1,'intval');
		$total = M('member_account')->where(array('uid' => $uid,'pay'=>'福分'))->count();
		$setPage = $this->getLimit($total,$page,20);
		$TotalPager = $setPage['totalPage'];
		$limit = $setPage['limit'];
		$account = $this->excq("select * from `@#_member_account` where `uid`='$uid' and `pay` = '福分' ORDER BY time DESC $limit",2);
		$conf = require INC_PATH.'/member/lib/user_fufen.ini.php';
		$fufen_to_money  = intval($member['score'] / $conf['fufen_yuan']);
		foreach ($account as $key => $value){
			$account[$key]['time'] = str_replace(' ', '<br />', date('Y-m-d H:i:s',$value['time']));
		}
		$this->ajaxReturn(array('status' => 1,'totalPager' => $TotalPager,'fufen_to_money' => $member['score'],'data' => $account));
	}
	
	//ajax发手机验证码
	private function sendcode($_type){
		$this->getUserinfo();
		$member=$this->userinfo;
		$mobile = $_POST['mobile'];
		$uid = $this->userinfo['uid'];
		if (!_checkmobile($mobile)){
			$this->ajaxReturn(array('status' => 0,'msg' => '手机号码格式不正确'),'json');
		}
		if ($member['mobile'] != $mobile){
			$this->ajaxReturn(array('status' => 0,'msg' => '手机号与当前手机号不同'),'json');
		}
		$Now = strtotime(date('Y-m-d').' 00:00:00');
		$count = M('sms_activity_code')->where(array('time' => array('GT',$Now),'type'=> $_type,'uid' => $member['uid']))->count();
		if ($count >= 5){
			$this->ajaxReturn(array('status' => 9,'msg' => '当前动态码次数用完'),'json');
		}
		
		if(!$uid){
			return array('status' => 0,'msg' => "发送用户手机认证码,用户ID不能为空！");
		}
		
		if(!$mobile){
			return array('status' => 0,'msg' => "发送用户手机认证码,手机号码不能为空!");
		}
		
		$mobilecodes = mt_rand(100000,999999);//验证码
		/*
		if ($_type == 1){
			$template = M('caches')->where(array('key' => 'template_mobile_set'))->getField('value');
			if (empty($template)){
				$content = '你在'.getConfig('web_name')."的短信验证码是:：{$mobilecodes}，请您注意查收！【".getConfig('sms_sign')."】";
			}else{
				$content = str_replace('000000', $mobilecodes, $template);
			}
		}elseif ($_type == 2){
			$template = M('caches')->where(array('key' => 'template_mobile_apply'))->getField('value');
			if (empty($template)){
				$content = '你在'.getConfig('web_name')."的短信验证码是:：{$mobilecodes}，请您注意查收！【".getConfig('sms_sign')."】";
			}else{
				$content = str_replace('000000', $mobilecodes, $template);
			}
		}
		$data = array(
				'uid' => $uid,
				'mobile' => $mobile,
				'code' => $mobilecodes,
				'type' => $_type,
				'status' => 0,
				'active_time' => 3600,	//一个小时内
				'time' => NOW_TIME
		);
		$model = M('sms_activity_code');
		$model->data($data)->add();
		$insert_id = $model->getLastInsID();
		$sends = new sms();
		//返回0发送成功
		if ($sends->sendSms($content,$mobile) == 0){
			$this->ajaxReturn(array('status' => 1,'msg' => '验证码发送成功'),'json');
		}else{
			M('sms_activity_code')->where(array('id' => $insert_id))->delete();
			$this->ajaxReturn(array('status' => 0,'msg' => '验证码发送失败'),'json');
		}
		*/
		$this->ajaxReturn(send_mobile_set_code($member['mobile'],$member['uid'],$_type),'json');
	}
	
	//用户服务协议
	private function terms(){
// 		$category=$this->excq("select * from `@#_category` where `parentid`='1' and `name`='新手指南'");
// 		p($category);
// 		exit;
		$article=$this->excq("select * from `@#_article` where `id`='53'");
		$this->ajaxReturn($article);
	}
	
	private function privatetext(){
		$article=$this->excq("select * from `@#_article` where id=54");
		$this->ajaxReturn($article);
	}
	
	private function newso(){
		$article=$this->excq("select * from `@#_article` where id=53");
		$this->ajaxReturn($article);
	}
	
	//检测用户是否已注册
	private function checkname(){
		$config_email = include_once APP_CORE.'/config/email.inc.php';
		$config_mobile = include_once APP_CORE.'/config/mobile.inc.php';	
		$name= isset($_GET['mobile'])?$_GET['mobile']:'';
		if(!_checkmobile($name)){
			$user['state']=1;//_message("系统短息配置不正确!");
			$this->ajaxReturn($user);
			exit;
		}
	
		$regtype=null;
		if(_checkmobile($name)){
			$regtype='mobile';
			$cfg_mobile_type  = 'cfg_mobile_'.$config_mobile['cfg_mobile_on'];
			$config_mobile = $config_mobile[$cfg_mobile_type];
			if(empty($config_mobile['mid']) && empty($config_email['mpass'])){
				$user['state']=2;//_message("系统短息配置不正确!");
				$this->ajaxReturn($user);
				exit;
			}
		}
		$member=$this->excq("SELECT * FROM `@#_member` WHERE `mobile` = '$name' LIMIT 1");
		if(is_array($member)){
			if($member['mobilecode']==1 || $member['emailcode']==1){
				$user['state']=1;//_message("该账号已被注册");
			}else{
				$sql="DELETE from`@#_member` WHERE `mobile` = '$name'";
				$this->aud($sql);
				$user['state']=0;
			}
		}else{
			$user['state']=0;//表示数据库里没有该帐号
		}
	
		$this->ajaxReturn($user);
	}
	
	//将数据注册到数据库
	private function usermobile(){
		if (empty($_GET['username']) || empty($_GET['password'])){
			$userMobile['state']=3;
			$this->ajaxReturn($userMobile);
		}
		$name= I('get.username');
		if (empty($_GET['password'])){
			$pass = md5('123456');
		}else{
			$pass = md5(base64_decode($_GET['password']));
		}
		
		$time=time();
		$decode = 0;
// 		if (isset($_COOKIE['regcode']) && !empty($_COOKIE['regcode'])){
// 			$decode=_encrypt($_COOKIE['regcode'],"DECODE");
// 			$decode = intval($decode);
// 		}
		//邮箱验证 -1 代表未验证， 1 验证成功 都不等代表等待验证
		$sql="INSERT INTO `@#_member`(`mobile`,password,img,emailcode,mobilecode,yaoqing,time)VALUES('$name','$pass','photo/member.jpg','-1','-1','$decode','$time')";
	
		if($this->aud($sql)){
			$userMobile['state']=0;
			$uid = $this->insert_id;
			if ($decode != 0){
// 				$userModel = M('Member');
// 				//邀请人获得积分
// 				$member_ini = include './'.APP_NAME.'/'.MODULE_PATH.'/member/lib/user_fufen.ini.php';
// 				$userModel->where(array('uid' => $decode))->setInc('score',$member_ini['z_visituser']);
// 				M('member_account')->add(array('uid' => $decode,'type' => 1,'pay' => '福分','content' => '邀请好友奖励','money' => $member_ini['z_visituser'],'time' => NOW_TIME));
			}
			$status = send_mobile_reg_code($name,$uid);
			$status['state'] = 0;
			$this->ajaxReturn($status);
			
		}else{
			$userMobile['state']=1;
		}	
		//_setcookie('regcode', null);
		$this->ajaxReturn($userMobile);
	}
	
	//验证输入的手机验证码
	private function mobileregsn(){
		
		if (!isset($_GET['mobile']) || !_checkmobile($_GET['mobile'])){
			$mobileregsn['state']=3;
			$this->ajaxReturn($mobileregsn);
		}

		if(!isset($_GET['code']) || strlen($_GET['code'])!=6){
			$mobileregsn['state']=1;
			$this->ajaxReturn($mobileregsn);
		}
		$mobile= $_GET['mobile'];
		$checkcodes= $_GET['code'];
	
		$member=$this->excq("SELECT * FROM `@#_member` WHERE `mobile` = '$mobile' LIMIT 1");
	
		$usercode=explode("|",$member['mobilecode']);
		if($checkcodes!=$usercode[0]){
			$mobileregsn['state']=1;
			$this->ajaxReturn($mobileregsn);
		}
	
	
		$this->aud("UPDATE `@#_member` SET mobilecode='1' where `uid`='$member[uid]'");
		$this->aud("UPDATE `@#_member` SET score='100' where `uid`='$member[uid]'");
	
	
		//_setcookie("uid",_encrypt($member['uid']),60*60*24*7);
		//_setcookie("ushell",_encrypt(md5($member['uid'].$member['password'].$member['mobile'].$member['email'])),60*60*24*7);
	
		$mobileregsn['state']=0;
		$mobileregsn['str']=1;
		$mobileregsn['uid'] = _encrypt($member['uid']);
		$mobileregsn['ushell'] = _encrypt(md5($member['uid'].$member['password'].$member['mobile'].$member['email']));
		$mobileregsn['email'] = $member['email'];
		$mobileregsn['mobile'] = $member['mobile'];
		$mobileregsn['username'] = $member['username'];
		$mobileregsn['qianming'] = $member['qianming'];
		$mobileregsn['money'] = $member['money'];
		$mobileregsn['score'] = $member['score'];
		$mobileregsn['face'] = $member['img'];
		
		//_setcookie('return_url', null);
		$mobileregsn['return_url'] = '';
	
		$this->ajaxReturn($mobileregsn);
	}
	
	//发送验证码
	public function sendmobile(){
		if (!isset($_GET['mobile']) || !_checkmobile($_GET['mobile'])){
			$sendmobile['state']=1;
			$this->ajaxReturn($sendmobile);
		}
		$name = $_GET['mobile'];
		$member= query("SELECT * FROM `@#_member` WHERE `mobile` = '$name' LIMIT 1");
		if(!$member){
			$sendmobile['state']=1;
			$this->ajaxReturn($sendmobile);
		}
		$checkcode=explode("|",$member['mobilecode']);
		$times=time()-$checkcode[1];
		if($times > 120){
			$sendok = send_mobile_reg_code($name,$member['uid']);
			if($sendok['status']!=1){
				$sendmobile['state']=1;
				$this->ajaxReturn($sendmobile);
			}
			//成功
			$sendmobile['state']=0;
			$this->ajaxReturn($sendmobile);
		}else{
			$sendmobile['state']=1;
			$this->ajaxReturn($sendmobile);
		}
	}
	
	//app首页获取即将揭晓倒计时
	private function appajaxshow(){
		//即将揭晓
		//Y
		$okShow = $this->model->query("select $this->field from `".C('DB_PREFIX')."shoplist` where `q_user_code` is not null and `q_showtime`= 'Y' limit 1");
		if (empty($okShow)){
			$result = json_encode(array('error' => 0));
			$this->ajaxReturn($result);
		}else{
			$okShow['error'] = 1;
			$okShow['q_end_time'] = ceil($okShow['q_end_time'])-time();
			$result = json_encode($okShow);
			$this->ajaxReturn($result);
		}
	}

	//获取网站基本信息
	private function getsite(){
		if (isset($_GET['key']) && !empty($_GET['key'])){
			$this->ajaxReturn(array('status' => 1,'data' => getConfig($_GET['key'])));
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => 'error'));
		}
	}
	
	//找回密码，重置密码
	private function resetpassword(){
		if(isset($_POST['submit'])){
			if ($_POST['userpassword'] != $_POST['userpassword2']){
				$this->ajaxReturn(array('status' => 0,'msg' => '两次密码输入不一致'),'json');
			}
			if (isset($_POST['mobile'])){
				$mc = safe_replace($_POST['mobile']);
			}
			$password=md5($_POST["userpassword"]);
			$passcode = safe_replace($_POST['passcode']);
			if(_checkemail($mc)){
				$sql="select * from `@#_member` where `email`='$mc' AND `passcode`= '$passcode' LIMIT 1";
			}elseif (_checkmobile($mc)){
				$sql="select * from `@#_member` where `mobile`='$mc' AND `passcode`= '$passcode' LIMIT 1";
			}
			$member= $this->excq($sql);
			if(!$member){
				$this->ajaxReturn(array('status' => 0,'msg' => '未知错误'),'json');
			}
			if ($this->aud("UPDATE `@#_member` SET `password`='$password',`passcode`='-1',`mobilecode`='1' where `uid`='$member[uid]'")){
				$this->ajaxReturn(array('status' => 1,'msg' => '重置密码成功'),'json');
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '重置密码失败'),'json');
			}
			
		}
	}
	
	//找回密码
	private function findpassword(){
		if(isset($_POST['submit'])){
			$name=isset($_POST['name']) ? $_POST['name'] : "";
// 			$txtRegSN=strtoupper($_POST['txtRegSN']);
// 			if(md5($txtRegSN)!=_getcookie('checkcode')){
// 				//验证码不正确
// 			}
			$regtype=null;
			if(_checkmobile($name)){
				$regtype='mobile';
			}
			if(_checkemail($name)){
				$regtype='email';
			}
			if($regtype==null){
				$this->ajaxReturn(array('status' => 0,'msg' => '帐号类型不正确'),'json');
			}
			$info=$this->excq("SELECT * FROM `@#_member` WHERE $regtype = '$name' LIMIT 1");
			if(!$info){
				$this->ajaxReturn(array('status' => 0,'msg' => '帐号不存在'),'json');
			}
			$randcode=rand(100000,999999);
			$checkcodes=$randcode.'|'.time();//验证码
			$this->aud("UPDATE `@#_member` SET passcode='$checkcodes',mobilecode='$checkcodes' where `uid`='$info[uid]'");
			/*
			$temp_m_pwd = $this->excq("select value from `@#_caches` where `key` = 'template_mobile_pwd' LIMIT 1");
			$text=str_replace("000000",$randcode,$temp_m_pwd['value']);
			$sendok = _renhu_sendmobile($name,$text);
			*/
			$sendok = send_mobile_sms($name,array($randcode),FIND_PWD_TPL);
			if($sendok['status'] == 0){
				$this->ajaxReturn(array('status' => 0,'msg' => $sendok['msg']),'json');
			}elseif ($sendok['status'] == 1){
				$this->ajaxReturn(array('status' => 1,'url' => '?act=findmobilecheck&name='.$info['mobile']),'json');
			}
		}
	}
	
	//手机找回密码
	public function findmobilecheck(){
		
		if (!isset($_GET['name'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '手机号码不存在'));
		}
		$name = $_GET['name'];
		if(!_checkmobile($name)){
			$this->ajaxReturn(array('status' => 0,'msg' => '手机号码格式不正确'));
		}
		$member= $this->excq("SELECT * FROM `@#_member` WHERE `mobile` = '$name' LIMIT 1");
		if(!$member){
			$this->ajaxReturn(array('status' => 0,'msg' => '用户不存在'));
		}
		
		$this->ajaxReturn(array('status' => 1,'data' => $name));
	}
		
	//检测验证码
	private function checkcode(){
		
		if(isset($_POST['submit'])){
			if (!isset($_POST['mobileCode']) || empty($_POST['mobileCode'])){
				$this->ajaxReturn(array('status' => 0,'msg' => '未知错误1'),'json');
			}
			if (!isset($_POST['mobile']) || empty($_POST['mobile'])){
				$this->ajaxReturn(array('status' => 0,'msg' => '未知错误2'),'json');
			}
			$mobileCode = $_POST['mobileCode'];
			$mobile = $_POST['mobile'];
			if (!_checkmobile($mobile)){
				$this->ajaxReturn(array('status' => 0,'msg' => '手机号码不正确'),'json');
			}
			
			$checkcodes=isset($_POST['mobileCode']) ? $_POST['mobileCode'] : $this->ajaxReturn(array('status' => 0,'msg' => '请输入验证码'),'json');
			if(strlen($checkcodes)!=6){
				$this->ajaxReturn(array('status' => 0,'msg' => '验证码输入不正确'),'json');
			}
			$member = M('member')->where(array('mobile' => $mobile))->find();
			$usercheck=explode("|",$member['passcode']);
			if ($usercheck[0]!=$checkcodes){
				$this->ajaxReturn(array('status' => 0,'msg' => '验证码输入不正确'),'json');
			}
			$timec=time()-$usercheck[1];
			if($timec<(3600*24)){
				$this->ajaxReturn(array('status' => 1,'data' => $member['passcode'],'msg' => '重置密码'),'json');
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '验证失败'),'json');
			}
		}
		
	}
	
	//找回密码重新发送验证码
	public function findsendmobile(){
		$name=isset($_GET['name'])?$_GET['name']:'';
		if (!$name) $this->ajaxReturn(array('status' => 0,'msg' => '手机号码不存在'));
		$member= $this->excq("SELECT * FROM `@#_member` WHERE `mobile` = '$name' LIMIT 1");
		if(!$member){
			$this->ajaxReturn(array('status' => 0,'msg' => '用户不存在'));
		}
		$checkcode=explode("|",$member['mobilecode']);
		$times=time()-$checkcode[1];
		if($times > 120){
			//重发验证码
			$mobile_code=rand(100000,999999);
			$mobile_time=time();
			$mobilecodes=$mobile_code.'|'.$mobile_time;//验证码
			$this->aud("UPDATE `@#_member` SET mobilecode='$mobilecodes',passcode='$mobilecodes' where `uid`='$member[uid]'");
			/*
			$temp_m_pwd = $this->excq("select value from `@#_caches` where `key` = 'template_mobile_pwd' LIMIT 1");
			$text=str_replace("000000",$mobile_code,$temp_m_pwd['value']);
			$sendok = _renhu_sendmobile($name,$text);
			*/
			$sendok = send_mobile_sms($name,array($mobile_code),FIND_PWD_TPL);
			if($sendok['status'] == 0){
				$this->ajaxReturn($sendok);
			}elseif ($sendok['status'] == 1){
				$this->ajaxReturn($sendok);
			}
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '重发时间间隔不能小于2分钟'));
		}
	}
	
	//收货地址
	private function useraddress(){
		$this->getUserinfo('jsonp');
		$address_id = intval(I('address_id'));
		$uid = $this->uid;
		if (!intval($uid)){
			$this->ajaxReturn(array('status' => 0));
		}
		if ($address_id != 0 && $uid){
			$data = M('member_dizhi')->where(array('id' => $address_id,'uid' => $uid))->find();
		}else{
			$data = M('member_dizhi')->where(array('uid' => $uid))->select();
		}
		if (empty($data)){
			$this->ajaxReturn(array('status' => 1));
		}else{
			$this->ajaxReturn(array('status' => 2,'data' => $data));
		}
	}

	//添加收货地址
	private function addaddress(){
		$this->getUserinfo();
		$uid = $this->uid;
		if (!$uid || !M('Member')->where(array('uid' => $uid))->find()){
			$this->ajaxReturn(array('status' => 0,'msg' => '用户不存在'),'json');
		}
		$data = array(
			'uid' => $uid,
			'sheng' => I('province'),
			'shi' => I('city'),
			'xian' => I('area'),
			'jiedao' => I('jiedao'),
			'youbian' => I('zipcode'),
			'shouhuoren' => I('truename'),
			'mobile' => I('mobile'),
			'default' => I('_default'),
			'time' => NOW_TIME
		);
		$this->checkaddressinfo($data);
		if ($data['default'] == 'Y'){
			M('member_dizhi')->where(array('uid' => $uid))->setField('default','N');
		}
		if (M('member_dizhi')->add($data)){
			$this->ajaxReturn(array('status' => 1,'msg' => '新增地址成功'),'json');
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '新增地址失败'),'json');
		}
	}
	
	private function checkaddressinfo($data){
		if (empty($data['sheng'])) $this->ajaxReturn(array('status' => 0,'msg' => '请输入省份'),'json');
		if (empty($data['shi'])) $this->ajaxReturn(array('status' => 0,'msg' => '请输入城市'),'json');
		if (empty($data['xian'])) $this->ajaxReturn(array('status' => 0,'msg' => '请输入区域'),'json');
		if (empty($data['jiedao'])) $this->ajaxReturn(array('status' => 0,'msg' => '请输入详细地址'),'json');
		if (empty($data['shouhuoren'])) $this->ajaxReturn(array('status' => 0,'msg' => '请输入收货人'),'json');
		if (!_checkmobile($data['mobile'])) $this->ajaxReturn(array('status' => 0,'msg' => '手机号码格式不正确'),'json');
	}
	
	//修改收货地址
	private function updateaddress(){
		$this->getUserinfo();
		$uid = $this->uid;
		$id = I('get.id',0,'intval');
		if (!$id || !$uid){
			$this->ajaxReturn(array('status' => 0,'msg' => '地址不存在'),'json');
		}else{
			if (isset($_POST['send'])){
			$data = array(
				'sheng' => I('province'),
				'shi' => I('city'),
				'xian' => I('area'),
				'jiedao' => I('jiedao'),
				'youbian' => I('zipcode'),
				'shouhuoren' => I('truename'),
				'mobile' => I('mobile'),
			);
			$this->checkaddressinfo($data);
			if (M('member_dizhi')->where(array('id' => $id))->save($data)){
				$this->ajaxReturn(array('status' => 1,'msg' => '保存成功'),'json');
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '保存失败'),'json');
			}
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '保存失败'),'json');
			}
		}
	}
	
	//获取当前商品时时进度
	private function tget_progress(){
		$itemid = intval(safe_replace($_GET['goods_id']));
		if (!$itemid) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		$item= $this->excq("select * from `".C('DB_PREFIX')."teamgoods` where `id`='".$itemid."' LIMIT 1");
		if(!$item){
			//status 0 商品不存在
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$item['progress'] = $item['canyurenshu']/$item['zongrenshu']*100;
		$item['percent'] = '已完成'.percent($item['canyurenshu'],$item['zongrenshu']);
		$item['yurenshu'] = $item['zongrenshu']-$item['canyurenshu'];
		$item['autoTime'] = intval($item['q_end_time']-time());
		if($item['q_end_time']){
			$item['q_end_time'] = microt($item['q_end_time']);
			$item['q_user'] = unserialize($item['q_user']);
			$gorecord = M('member_team_record')->where(array('uid' => $item['q_uid'],
					'shopid' => $item['id'],
					'goucode' => array('LIKE',"%{$item['q_user_code']}%")))->find();
			$item['gorecode_time'] = microt($gorecord['time']);
			$item['gonumber'] = $gorecord['gonumber'];
		}
		$this->ajaxReturn(array('status' => 1,'item' => $item));
	}
	
	//获取当前商品时时进度
	private function get_progress(){
		$itemid = intval(safe_replace($_GET['goods_id']));
		if (!$itemid) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		$item= $this->excq("select * from `".C('DB_PREFIX')."shoplist` where `id`='".$itemid."' LIMIT 1");
		if(!$item){
			//status 0 商品不存在
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$item['progress'] = $item['canyurenshu']/$item['zongrenshu']*100;
		$item['percent'] = '已完成'.percent($item['canyurenshu'],$item['zongrenshu']);
		$item['yurenshu'] = $item['zongrenshu']-$item['canyurenshu'];
		$item['autoTime'] = intval($item['q_end_time']-time());
		
		//最新期数
		$itemlist = $this->excq("select id,qishu from `@#_shoplist` where sid={$item['sid']} and qishu > {$item['qishu']} order by qishu desc",2);
		$loopqishu = '';
		if(!empty($itemlist)){
			foreach($itemlist as $qitem){
				$loopqishu .='<li><a href="javascript:openItem(\'item\','.$qitem['id'].',function(id){localData.set(\'goods_id\','.$qitem['id'].');});" class="">第'.$qitem['qishu'].'期</a></li>';
			}
		}
		$this->ajaxReturn(array('status' => 1,'item' => $item,'qishu' => $loopqishu));
	}
	
	//商品详细
	private function item(){
		$itemid = intval(safe_replace($_GET['goods_id']));
		if (!$itemid) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		$item= $this->excq("select * from `".C('DB_PREFIX')."shoplist` where `id`='".$itemid."' LIMIT 1");
		if(!$item){
			//status 0 商品不存在
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$sid=$item['sid'];
		if(!empty($item['q_end_time'])){
			if($item['q_end_time']-time() <= 0){
				//status -1 商品已揭晓
				//$this->ajaxReturn(array('status' => -1,'msg' => '商品已揭晓','url' => '/app.php?act=dataserver&goods_id='.$item['id']));
				//$item = $this->excq("select * from `".C('DB_PREFIX')."shoplist` where `sid`='".$sid."' order by `id` DESC LIMIT 1");
			}
			//file_put_contents('sql.txt', "select * from `".C('DB_PREFIX')."shoplist` where `qishu`>'{$item['qishu']}' and `sid`='{$item['sid']}' and `q_end_time` is null LIMIT 1");
			//$item = $this->excq("select * from `".C('DB_PREFIX')."shoplist` where `qishu`>'{$item['qishu']}' and `sid`='{$item['sid']}' and `q_end_time` is null LIMIT 1");
		}

		
		$sid_code=$this->excq("select * from `".C('DB_PREFIX')."shoplist` where `sid`='$sid' order by `id` DESC LIMIT 1,1");
		$sid_go_record=$this->excq("select * from `".C('DB_PREFIX')."member_go_record` where `shopid`='$sid_code[sid]' and `uid`='$sid_code[q_uid]' order by `id` DESC LIMIT 1");

		$category=$this->excq("select * from `@#_category` where `cateid` = '$item[cateid]' LIMIT 1");
		$brand=$this->excq("select * from `@#_brand` where `id`='$item[brandid]' LIMIT 1");
	
		$title=$item['title'];
		$syrs=$item['zongrenshu']-$item['canyurenshu'];
		$item['picarr'] = unserialize($item['picarr']) ;
		$us=$this->excq("select * from `@#_member_go_record` where `shopid`='".$itemid."' AND `shopqishu`='".$item['qishu']."'ORDER BY id DESC LIMIT 6",2);
		$itemlist = $this->excq("select * from `@#_shoplist` where `sid`='$item[sid]' and `q_end_time` is not null and `id` != '{$item['id']}' order by `qishu` DESC",2);
		
		//期数显示
		$loopqishu=array();
		$itemlists = $this->excq("select id,qishu from `@#_shoplist` where sid={$item['sid']} and qishu > {$item['qishu']} order by qishu desc",2);
		foreach ($itemlists as $value){
			$loopqishu[] ='<li><a href="javascript:openItem(\'item\','.$value['id'].',function(id){localData.set(\'goods_id\','.$value['id'].');});" class="">第'.$value['qishu'].'期</a></li>';
		}
		$loopqishu[]='<li class="cur"><a href="javascript:;">'."第".$item['qishu']."期</a><b></b></li>";	
		foreach($itemlist as $qitem){
			$loopqishu[]='<li><a href="javascript:openItem(\'dataserver\','.$qitem['id'].',function(id){localData.set(\'dataserver_goods_id\','.$qitem['id'].');});" >第'.$qitem['qishu'].'期</a></li>';
		}
		
		$gorecode=array();
		if(!empty($itemlist)){
			//查询上期的获奖者信息
			$gorecode=$this->excq("select * from `@#_member_go_record` where `shopid`='".$itemlist[0]['id']."' AND `shopqishu`='".$itemlist[0]['qishu']."' and huode!=0 ORDER BY id DESC LIMIT 1");
		}

		$curtime=time();
		$shopitem='itemfun';

		//晒单数
		$shopid=$this->excq("select * from `@#_shoplist` where `id`='$itemid'");
		$shoplist=$this->excq("select * from `@#_shoplist` where `sid`='$shopid[sid]'",2);
		$shop='';
		foreach($shoplist as $list){
			$shop.=$list['id'].',';
		}
		$id=trim($shop,',');
		if($id){
			$shaidan=$this->excq("select * from `@#_shaidan` where `sd_shopid` IN ($id)",2);
			$sum=0;
			foreach($shaidan as $sd){
				$shaidan_hueifu=$this->excq("select * from `@#_shaidan_hueifu` where `sdhf_id`='$sd[sd_id]'",2);
				$sum=$sum+count($shaidan_hueifu);
			}
		}else{
			$shaidan=0;
			$sum=0;
		}
		
		//上期记录
		$gorecode = $this->excq("select * from `@#_shoplist` where sid=".$item['sid']." and qishu < ".$item['qishu']." and `q_showtime`='N' and q_uid is not null order by qishu desc limit 1");
		$gorecode_count = 0;
		$gorecode_time = '';
		if(!empty($gorecode)){
			$gorecode_count=$this->excq("select sum(gonumber) as count from `@#_member_go_record` where `shopid`='".$gorecode['id']."' AND `shopqishu`='".$gorecode['qishu']."' and `uid`='$gorecode[q_uid]'");
			$gorecode_count=$gorecode_count ? $gorecode_count['count'] : 0;
			$gorecode_time = $this->excq("select * from `@#_member_go_record` where `shopid`='".$gorecode['id']."' AND `shopqishu`='".$gorecode['qishu']."' and `uid`='$gorecode[q_uid]' and `huode` = '$gorecode[q_user_code]' limit 1");
		}
		
		$item['progress'] = $item['canyurenshu']/$item['zongrenshu']*100;
		$item['percent'] = '已完成'.percent($item['canyurenshu'],$item['zongrenshu']);
		$item['yurenshu'] = $item['zongrenshu']-$item['canyurenshu'];
		$item['autoTime'] = intval($item['q_end_time']-time());
		$arr = array(
			'gorecode' => array('isEmpty' => '')
		);
		if (!empty($gorecode)){
			$userinfo = unserialize($gorecode['q_user']);
			$gorecode['userimg'] = $userinfo['img'];
			$arr = array(
			'gorecode' => array(
				'isEmpty' => $gorecode,
				'gorecode_count' => $gorecode_count,
				'username' => get_user_name($gorecode['q_uid']),
				'ip' => get_ip($gorecode_time['id'],'ipcity'),
				'opencode_time' => microt($gorecode['q_end_time']),
				'gorecode_time' => microt($gorecode_time['time']))
			);
		}
		$data = array('status' => 1,
				'item' => $item,
				'list' => $loopqishu,
				'sunOrder' => array('count' => count($shaidan),'comment' => $sum),
		);
		
		$data = array_merge($data,$arr);
		$this->ajaxReturn($data);
	}

	//查看计算结果时间列表
	private function getcalresult(){
		$itemid= intval($_GET['goods_id']);
		if (!$itemid){
			$this->ajaxReturn(array('status' => 0,'msg' => '数据不存在'));
		}
		$curtime=time();
	
		$item=$this->excq("select * from `@#_shoplist` where `id`='$itemid' and `q_end_time` is not null LIMIT 1");
	
		if($item['q_content']){
			$item['contcode']=0;
			$item['itemlist'] = unserialize($item['q_content']);
			foreach($item['itemlist'] as $key=>$val){
				$item['itemlist'][$key]['time']	=microt($val['time']);
				$h=date("H",$val['time']);
				$i=date("i",$val['time']);
				$s=date("s",$val['time']);
				list($timesss,$msss) = explode(".",$val['time']);
				
				$item['itemlist'][$key]['timecode']=$h.$i.$s.$msss;
			}
	
		}else{
			$item['contcode']=1;
		}
	
		if(!empty($item)){
			$item['code']=0;
	
		}else{
			$item['code']=1;
		}
		$this->ajaxReturn($item);
	}
	
	//计算结果
	private function calresult(){
		$itemid= intval($_GET['goods_id']);
		if (!$itemid){
			$this->ajaxReturn(array('status' => 0,'msg' => '数据不存在'));
		}
		$item= $this->excq("select * from `@#_shoplist` where `id`='$itemid' LIMIT 1");
		$h=abs(date("H",$item['q_end_time']));
		$i=date("i",$item['q_end_time']);
		$s=date("s",$item['q_end_time']);
		$w=substr($item['q_end_time'],11,3);
		$user_shop_time_add = $h.$i.$s.$w;
		$user_shop_fmod = fmod($user_shop_time_add*100,$item['canyurenshu']);
	
		$time_total = $user_shop_time_add*100;
		$user_shop_time_add = $time_total+$item['opencode'];
	
		if($item['q_content']){
			$item['q_content'] = unserialize($item['q_content']);
			$user_shop_time_add = $item['q_counttime'];
			$user_shop_fmod = fmod($item['q_counttime'],$item['canyurenshu']);
		}
	
		$user_shop_fmod = $item['q_user_code']-10000001;
	
		$item['picarr'] = unserialize($item['picarr']) ;
		unset($item['q_content']);
		if (empty($item)){
			$this->ajaxReturn(array('status' => 0));
		}
		$item['q_end_time'] = microt($item['q_end_time']);
		$this->ajaxReturn(array('status' => 1,
				'data' => $item,
				'time_total' => $time_total,
				'user_shop_fmod' => $user_shop_fmod,
				'user_shop_time_add' => $user_shop_time_add
		));
	}
	
	//商品详情购买记录
	private function buyrecordsajax(){
		$itemid= intval($_GET['goods_id']);
		if (!$itemid) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		$cords=$this->excq("select * from `@#_member_go_record` where `shopid`='$itemid'",2);
		if(!$cords){
			$this->ajaxReturn(array('status' => 0,'msg' => '暂无购买记录'));
		}
		foreach ($cords as $key => $value){
			if ($value['ip']){
				$cords[$key]['ip1'] = get_ip($value['id'],'ipcity');
				$cords[$key]['ip2'] = get_ip($value['id'],'ipmac');
			}
			$cords[$key]['web_name_two'] = getConfig('web_name_two');
			$cords[$key]['time'] = microt($value['time']);
		}
		$this->ajaxReturn(array('status' => 1,'data' => $cords));
	}
	
	//图文详细
	private function goodsdesc(){
		$itemid= intval($_GET['goods_id']);
		if (!$itemid) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		$desc=$this->excq("select * from `@#_shoplist` where `id`='$itemid'");
		if(!$desc){
			 $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$this->ajaxReturn(array('status' => 1,'html' => $desc['content']));
	}
	//图文详细
	private function tgoodsdesc(){
		$itemid= intval($_GET['goods_id']);
		if (!$itemid) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		$desc=$this->excq("select * from `@#_teamgoods` where `id`='$itemid'");
		if(!$desc){
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$this->ajaxReturn(array('status' => 1,'html' => $desc['content']));
	}
	private function zdesc(){
		$itemid= intval($_GET['goods_id']);
		if (!$itemid) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		$desc=$this->excq("select * from `@#_jf_shoplist` where `id`='$itemid'");
		if(!$desc){
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$this->ajaxReturn(array('status' => 1,'html' => $desc['content']));
	}
	//团揭晓计算结果
	private function teamcalresult(){
		$itemid = intval($_GET['goods_id']);
		$item=$this->excq("select * from `@#_teamgoods` where `id`='$itemid' LIMIT 1");
		if(empty($item)){
			$this->ajaxReturn(array('status' => 0,'msg' => '参数错误'));
		}
		$h=abs(date("H",$item['q_end_time']));
		$i=date("i",$item['q_end_time']);
		$s=date("s",$item['q_end_time']);
		$w=substr($item['q_end_time'],11,3);
		$user_shop_time_add = $h.$i.$s.$w;
		//echo $user_shop_time_add*100+$item['opentime'];
		$user_shop_fmod = fmod($user_shop_time_add*100,$item['canyurenshu']);
		$time_total = $user_shop_time_add*100;
		$user_shop_time_add = $time_total+$item['opencode'];
		if($item['q_content']){
			$item['q_content'] = unserialize($item['q_content']);
			$user_shop_time_add = $item['q_counttime'];
			$user_shop_fmod = fmod($item['q_counttime'],$item['canyurenshu']);
		}
		$user_shop_fmod = $item['q_user_code']-10000001;
		$item['picarr'] = unserialize($item['picarr']) ;
		$this->ajaxReturn(array('status' => 1,
				'hidRaffleTime' => microt($item['q_end_time']),
				'hidBaseNum' => $user_shop_time_add,
				'hidYuShu' => $user_shop_fmod,
				'total_time' => $time_total,
				'item' => $item));
	}
	
	//查看计算结果
	private function teamgetcalresult(){
		$itemid = intval($_GET['goods_id']);
		$curtime=time();
		$item=$this->excq("select * from `@#_teamgoods` where `id`='$itemid' and `q_end_time` is not null LIMIT 1");
		if($item['q_content']){
			$item['contcode']=0;
			$item['itemlist'] = unserialize($item['q_content']);
			foreach($item['itemlist'] as $key=>$val){
				$item['itemlist'][$key]['time']	=microt($val['time']);
				$h=date("H",$val['time']);
				$i=date("i",$val['time']);
				$s=date("s",$val['time']);
				list($timesss,$msss) = explode(".",$val['time']);
				$item['itemlist'][$key]['timecode']=$h.$i.$s.$msss;
			}
		}else{
			$item['contcode']=1;
		}
		if(!empty($item)){
			$item['code']=0;
		}else{
			$item['code']=1;
		}
		$this->ajaxReturn($item);
	}
	
	//判断进团邀请码
	private function jointeamcheck(){
		$ShopId = intval($_GET['goods_id']);
		if($ShopId==0 || empty($_POST['code'])){
			$cart['code']=1;   //表示添加失败
			$cart['msg'] = '参数错误';
		}else{
			$goodsInfo = M('teamgoods')->where(array('id' => $ShopId))->field(array('q_create_uid','q_create_pwd'))->find();
			if ($goodsInfo['q_create_pwd'] != strtoupper($_POST['code'])){
				$cart['code'] = 1;   //表示添加失败
				$cart['msg'] = '邀请码不正确';
			}else{
				$cart['code']=0; //表示添加成功
				$cart['msg'] = '验证通过，尽快下手咯.';
			}
		}
		$this->ajaxReturn($cart,$this->json);
	}
	
	//往期商品查看
	private function dataserver(){
		$itemid= intval($_GET['goods_id']);
		if(!$itemid) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在！'));
		$item=$this->excq("select * from `@#_shoplist` where `id`='$itemid'  LIMIT 1");
		if(!$item){
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在！'));
		}
		if (!$item['q_end_time'] ) {
			$this->ajaxReturn(array('status' => -1,'msg' => '商品正在进行中！'));
		}
		
		if(empty($item['q_user_code'])){
			$this->ajaxReturn(array('status' => -1,'msg' => '该商品正在进行中...'));
		}
	
		$itemlist = $this->excq("select * from `@#_shoplist` where `sid`='$item[sid]' order by `qishu` DESC",2);
		$category= $this->excq("select * from `@#_category` where `cateid` = '$item[cateid]' LIMIT 1");
		$brand= $this->excq("select * from `@#_brand` where `id` = '$item[brandid]' LIMIT 1");
	
		//购买中奖码
		$q_user = unserialize($item['q_user']);
		$q_user_code_len = strlen($item['q_user_code']);
		$q_user_code_arr = array();
		for($q_i=0;$q_i < $q_user_code_len;$q_i++){
			$q_user_code_arr[$q_i] = substr($item['q_user_code'],$q_i,1);
		}
	
		//期数显示
		$loopqishu='';
		if(empty($itemlist[0]['q_end_time'])){
			if($itemlist[0]['isFree'] == 1){
				$loopqishu.='<div class="item"><a href="javascript:openItem(\'f_item\','.$itemlist[0]['id'].',function(id){localData.set(\'f_goods_id\',id);});">'."第".$itemlist[0]['qishu']."期</a><b></b></div>";
			}else{
				$loopqishu.='<div class="item"><a href="javascript:openItem(\'item\','.$itemlist[0]['id'].',function(id){localData.set(\'goods_id\',id);});">'."第".$itemlist[0]['qishu']."期</a><b></b></div>";
			}
			array_shift($itemlist);
		}
	
		foreach($itemlist as $qitem){
			if($qitem['id'] == $itemid){
				$loopqishu.='<div class="item current"><a href="javascript:;">'."第".$qitem['qishu']."期</a><b></b></div>";
			}else{
				$loopqishu.='<div class="item reloadpage"><a href="javascript:;" item="'.$qitem['id'].'">第'.$qitem['qishu'].'期</a></div>';
			}
		}
	
		//总购买次数
		$user_shop_number = 0;
		//用户购买时间
		$user_shop_time = 0;
		//得到购买码
		$user_shop_codes = '';
	
		$user_shop_list = $this->excq("select * from `@#_member_go_record` where `uid`= '$item[q_uid]' and `shopid` = '$itemid' and `shopqishu` = '$item[qishu]'",2);
		foreach($user_shop_list as $user_shop_n){
			$user_shop_number += $user_shop_n['gonumber'];
			if($user_shop_n['huode']){
				$user_shop_time = $user_shop_n['time'];
				$user_shop_codes = $user_shop_n['goucode'];
			}
		}
		$h=abs(date("H",$item['q_end_time']));
		$i=date("i",$item['q_end_time']);
		$s=date("s",$item['q_end_time']);
		$w=substr($item['q_end_time'],11,3);
		$user_shop_time_add = $h.$i.$s.$w;
		$user_shop_fmod = fmod($user_shop_time_add*100,$item['canyurenshu']);
	
		if($item['q_content']){
			$item['q_content'] = unserialize($item['q_content']);
		}
		$item['picarr'] = unserialize($item['picarr']) ;
	
		//最新一期正在进行中
		$itemzx= $this->excq("select $this->field from `@#_shoplist` where `sid`='$item[sid]' and `qishu`>'$item[qishu]' and `q_end_time` is null order by `qishu` DESC LIMIT 1");
	
		$gorecode = $this->excq("select * from `@#_shoplist` where sid=".$item['sid']." and qishu < ".$item['qishu']." and q_uid is not null order by qishu desc limit 1");
		$gorecode_count=$this->excq("select sum(gonumber) as count from `@#_member_go_record` where `shopid`='".$gorecode['id']."' AND `shopqishu`='".$gorecode['qishu']."' and `uid`='$gorecode[q_uid]'");
		$gorecode_count=$gorecode_count ? $gorecode_count['count'] : 0;
		$gorecode_time = $this->excq("select * from `@#_member_go_record` where `shopid`='".$item['id']."' AND `shopqishu`='".$item['qishu']."' and `uid`='$item[q_uid]' and `huode` = '$item[q_user_code]' limit 1");
		
		$item['progress'] = $item['canyurenshu']/$item['zongrenshu']*100;
		$item['percent'] = '已完成'.percent($item['canyurenshu'],$item['zongrenshu']);
		$item['yurenshu'] = $item['zongrenshu']-$item['canyurenshu'];
		
		$shopitem='dataserverfun';
		$curtime=time();
		//晒单数
		$shopid=$this->excq("select * from `@#_shoplist` where `id`='$itemid'");
		$shoplist=$this->excq("select * from `@#_shoplist` where `sid`='$shopid[sid]'",2);
		$shop='';
		foreach($shoplist as $list){
			$shop.=$list['id'].',';
		}
		$id=trim($shop,',');
		if($id){
			$shaidan=$this->excq("select * from `@#_shaidan` where `sd_shopid` IN ($id)",2);
			$sum=0;
			foreach($shaidan as $sd){
				$shaidan_hueifu=$this->excq("select * from `@#_shaidan_hueifu` where `sdhf_id`='$sd[sd_id]'",2);
				$sum=$sum+count($shaidan_hueifu);
			}
		}else{
			$shaidan=0;
			$sum=0;
		}
		$itemxq=0;
		if(!empty($itemzx)){
			$itemxq=1;
		}
		
		if (!empty($gorecode)){
			$userinfo = unserialize($gorecode['q_user']);
			$gorecode['userimg'] = $userinfo['img'];
		}
		$item['user_shop_number'] = $user_shop_number;
		$item['autoTime'] = intval($item['q_end_time']-time());
		$item['q_end_time'] = microt($item['q_end_time']);
		$item['q_userimg'] = get_user_key($item['q_uid']);
		
		$data = array('status' => 1,
				'item' => $item,
				'action' => $itemzx,
				'list' => $loopqishu,
				'sunOrder' => array('count' => count($shaidan),'comment' => $sum),
				'gorecode' => array('isEmpty' => $gorecode,
						'gorecode_count' => $gorecode_count,
						'username' => get_user_name($gorecode['q_uid']),
						'ip' => get_ip($gorecode_time['id'],'ipcity'),
						'opencode_time' => $item['q_end_time'],
						'q_go_time' => microt($gorecode_time['time']))
		);
		$this->ajaxReturn($data);
		
	}
	
	//已晒单
	private function singlelist(){
		$FIdx=0;
		$EIdx=10;
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		
		if(isset($_GET['sd_ok_id']) && intval($_GET['sd_ok_id']) != 0){
			$order_id = intval($_GET['sd_ok_id']);
			$goods_id = M('member_go_record')->where(array('id' => $order_id))->getField('shopid');
			$map = ' and a.sd_shopid='.$goods_id;
			$postlist['listItems'] = $this->excq("select * from `@#_shaidan` a left join `@#_shoplist` b on a.sd_shopid=b.id where a.sd_userid='$member[uid]' $map limit 1");
			$list = false;
		}else{
			$list = true;
			$postlist['listItems'] = $this->excq("select * from `@#_shaidan` a left join `@#_shoplist` b on a.sd_shopid=b.id where a.sd_userid='$member[uid]' and a.sd_type=0 order by a.sd_time desc",2);
		}
		
		//$post= $this->excq("select * from `@#_shaidan` a left join `@#_shoplist` b on a.sd_shopid=b.id where a.sd_userid='$member[uid]' $map order by a.sd_time desc",2);
		//$postlist['listItems']=$this->db->GetList("select * from `@#_shaidan` a left join `@#_shoplist` b on a.sd_shopid=b.id where a.sd_userid='$member[uid]' order by a.sd_time desc limit $FIdx,$EIdx");

		if(empty($postlist['listItems'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '暂无数据'));
		}else{
			if ($list){
				foreach($postlist['listItems'] as $key=>$val){
					$postlist['listItems'][$key]['sd_time']=date('Y-m-d H:i',$val['sd_time']);
				}
			}else{
				$postlist['listItems']['sd_time'] = date('Y-m-d H:i',$postlist['listItems']['sd_time']);
			}
// 			$postlist['postCount'] = count($post);
			$this->ajaxReturn(array('status' => 1,'data' => $postlist));
		}
	}
	
	//未晒单
	public function singlelister(){
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		$cord= $this->excq("select * from `@#_member_go_record` where `uid`='$member[uid]' and `huode` > '10000000'",2);
	
		$shaidan= $this->excq("select * from `@#_shaidan` where `sd_userid`='$member[uid]' order by `sd_id`",2);
		$sd_id = $r_id = array();
		foreach($shaidan as $sd){
			if(!empty($sd['sd_shopid'])){
				$sd_id[]=$sd['sd_shopid'];
			}
		}
	
		foreach($cord as $rd){
			if(!in_array($rd['shopid'],$sd_id)){
				$r_id[]=$rd['shopid'];
			}
		}
		if(!empty($r_id)){
			$rd_id=implode(",",$r_id);
			$rd_id = trim($rd_id,',');
		}else{
			$rd_id="0";
		}
	
		$record = $this->excq("select a.shopid,a.id from `@#_member_go_record` as a left join `@#_shoplist` as b on a.shopid=b.id where a.shopid in ($rd_id) and a.`uid`='$member[uid]' and a.`huode`>'10000000' and b.q_showtime='N'",2);
	
// 		$total=$this->db->GetCount("select * from `@#_shaidan` where `sd_userid`='$member[uid]' order by `sd_id`");
// 		if(isset($_GET['p'])){$pagenum=$_GET['p'];}else{$pagenum=1;}
// 		$page=System::load_sys_class('page');
// 		$page->config($total,10,$pagenum,"0");
// 		$shaidan=$this->db->GetPage("select * from `@#_shaidan` where `sd_userid`='$member[uid]' order by `sd_id`",array("num"=>10,"page"=>$pagenum,"type"=>1,"cache"=>0));
		if (empty($record)){
			$this->ajaxReturn(array('status' => 0,'msg' => '暂无数据'));
		}else{
			foreach ($record as $key => $value) {
				$record[$key]['thumb'] = shoplisext($value['shopid'],'thumb');
				$record[$key]['title'] = shoplisext($value['shopid'],'title');
			}
			$this->ajaxReturn(array('status' => 1,'data' => $record));
		}
		
	}
	
	//晒单详情
	private function sddetail(){
		$sd_id= I('get.sd_id',0,'intval');
		if (!$sd_id) $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'));
	
		$shaidan= $this->excq("select * from `@#_shaidan` where `sd_id`='$sd_id'");
		if(!empty($shaidan['sd_shopid'])){
			if ($shaidan['sd_type'] == 1){
				$goods = $this->excq("select * from `@#_teamgoods` where `id` = '$shaidan[sd_shopid]' order by `qishu` DESC");
			}else{
				$goods = $this->excq("select * from `@#_shoplist` where `id` = '$shaidan[sd_shopid]' order by `qishu` DESC");
			}
		}else{
			//$goods = $this->db->GetOne("select * from `@#_jf_shoplist` where `sid` = '$shaidan[sd_shopid]' order by `qishu` DESC");
			$this->ajaxReturn(array('status' => 0,'msg' => '非法操作'));
		}
		$shaidannew=$this->excq("select * from `@#_shaidan` order by `sd_id` DESC limit 5",2);
		$shaidan_hueifu=$this->excq("select * from `@#_shaidan_hueifu` where `sdhf_id`='$sd_id'",2);
		if(!$shaidan){
			$this->ajaxReturn(array('status' => 0,'msg' => '页面错误'));
		}
	
		foreach ($shaidan_hueifu as $key => $value) {
			$shaidan_hueifu[$key]['u_thumb'] = get_user_key($value['sdhf_userid']);
			$shaidan_hueifu[$key]['u_username'] = get_user_name($value['sdhf_userid'], 'username');
			$shaidan_hueifu[$key]['sdhf_time'] = date('Y-m-d H:i:s',$value['sdhf_time']);
		}
	
		$img = '';
		if (!empty($shaidan['sd_photolist'])){
			if(strpos($shaidan['sd_photolist'], ';') > 0){
				$str = substr($shaidan['sd_photolist'], 0,-1);
				$img = explode(';', $str);
				$shaidan['imgs'] = 1;
			}else{
				$img = $shaidan['sd_photolist'];
				$shaidan['imgs'] = 0;
			}
		}
	
		$shaidan['u_thumb'] = get_user_key($shaidan['sd_userid']);
		$shaidan['u_username'] = get_user_name($shaidan['sd_userid']);
		$shaidan['q_user_code'] = $goods['q_user_code'];
		if ($shaidan['sd_type'] == 1){
			$count = M('member_team_record')->where(array('uid' => $shaidan['sd_userid'],'shopid' => $shaidan['sd_shopid']))->sum('gonumber');
		}else{
			$count = M('member_go_record')->where(array('uid' => $shaidan['sd_userid'],'shopid' => $shaidan['sd_shopid']))->sum('gonumber');
		}
	
		$shaidan['q_gonumber'] = $count?$count:0;
		$shaidan['q_end_time'] = date('Y-m-d H:i:s',$goods['q_end_time']);
		$shaidan['sd_photolist'] = $img;
		$shaidan['sd_time'] = date('Y-m-d H:i:s',$shaidan['sd_time']);
	
		$this->ajaxReturn(array('status' => 1,
				'data' => $shaidan,
				'comment' => $shaidan_hueifu,
				'comment_num' => count($shaidan_hueifu)
		));
	}
	
	//晒单上传
	private function singphotoup(){
		$this->getUserinfo();
		if(!empty($_FILES)){
			$upload = new UploadFile();
			$upload->maxSize = -1; //不限
			//$upload->allowExts = array('jpg','png','jpeg','gif');
			//$upload->allowTypes = array('image/jpeg'); //MIME
			$upload->thumb = true;
			$upload->thumbMaxWidth = '100';
			$upload->thumbMaxHeight = '100';
			$upload->autoSub = true;
			$upload->subType = 'date';
			$upload->dateFormat = 'Ymd';
			$upload->savePath = '../uploads/shaidan/';
			if ($upload->upload()){
				$info = current($upload->getUploadFileInfo());
				@list($dirname,$filename) = explode('/', $info['savename']);
				$newFilename = $filename.'jpg';
				rename($upload->savePath.$info['savename'], $upload->savePath.'/'.$dirname.'/'.$newFilename);
				$data = array(
					//'thumb' => 'shaidan/'.$dirname.'/thumb_'.$filename,
					'thumb' => 'shaidan/'.$dirname.'/'.$newFilename,
					//'path' => 'shaidan/'.$info['savename'],
					'path' => 'shaidan/'.$dirname.'/'.$newFilename,
				);
				$this->ajaxReturn(array('status' => 1,'data' => $data),'json');
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => $upload->getErrorMsg()),'json');
			}
		}
	}
	
	//添加晒单
	private function tsingleinsert(){
		if(isset($_POST['submit'])){
			$this->getUserinfo();
		}else{
			$this->getUserinfo('jsonp');
		}
		$member=$this->userinfo;
		$recordid= intval($_GET['sd_order_id']);
		if (!$recordid) $this->ajaxReturn(array('status' => 0,'msg' => '订单不存在'));
		$shaidan=$this->excq("select * from `@#_member_team_record` where `id`='$recordid' and `uid` = '$member[uid]'");
		if(!$shaidan){
			$this->ajaxReturn(array('status' => 0,'msg' => '该商品您不可晒单!'));
		}
		$shaidanyn=$this->excq("select sd_id from `@#_shaidan` where `sd_shopid`='$shaidan[shopid]' and `sd_type`='0' and `sd_userid` = '$member[uid]'");
		if($shaidanyn){
			$this->ajaxReturn(array('status' => 0,'msg' => '不可重复晒单!'));
		}
		$ginfo=$this->excq("select id,sid,qishu from `@#_teamgoods` where `id`='$shaidan[shopid]' LIMIT 1");
		if(!$ginfo){
			$this->ajaxReturn(array('status' => 0,'msg' => '该商品已不存在!'));
		}
	
		if(isset($_POST['submit'])){
			if(empty($_POST['title'])){
				$this->ajaxReturn(array('status' => 0,'msg' => '标题不能为空'),'json');
			}
			if(empty($_POST['content'])){
				$this->ajaxReturn(array('status' => 0,'msg' => '内容不能为空'),'json');
			}
			$pic = '';
			if (isset($_POST['fileurl_tmp'])){
				foreach ($_POST['fileurl_tmp'] as $key => $value) {
					$pic .= $value.';';
				}
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '请至少上传1张晒单照片！'),'json');
			}
				
			$sd_userid = $this->userinfo['uid'];
			$sd_shopid = $ginfo['id'];
			$sd_shopsid = $ginfo['sid'];
			$sd_qishu = $ginfo['qishu'];
			$sd_title = _htmtocode($_POST['title']);
				
			if(empty($_POST['shaitu'])){
				$sd_thumbs = $_POST['fileurl_tmp'][0];
			}else{
				$sd_thumbs = _htmtocode($_POST['shaitu']);
			}
				
			$sd_content = _htmtocode($_POST['content']);
			$sd_photolist= $pic;
			$sd_time=time();
			$sd_ip = _get_ip_dizhi();
			$this->aud("INSERT INTO `@#_shaidan`(`sd_userid`,`sd_shopid`,`sd_shopsid`,`sd_type`,`sd_qishu`,`sd_ip`,`sd_title`,`sd_thumbs`,`sd_content`,`sd_photolist`,`sd_time`)VALUES
					('$sd_userid','$sd_shopid','$sd_shopsid','1','$sd_qishu','$sd_ip','$sd_title','$sd_thumbs','$sd_content','$sd_photolist','$sd_time')");
	
			$this->ajaxReturn(array('status' => 1,'msg' => '晒单分享成功'),'json');
		}
	
		$this->ajaxReturn(array('status' => 1,'shopinfo' => $ginfo));
	}
	
	//添加晒单
	private function singleinsert(){
		if(isset($_POST['submit'])){
			$this->getUserinfo();
		}else{
			$this->getUserinfo('jsonp');
		}
		$member=$this->userinfo;
		$recordid= intval($_GET['sd_order_id']);
		if (!$recordid) $this->ajaxReturn(array('status' => 0,'msg' => '订单不存在'));
		$shaidan=$this->excq("select * from `@#_member_go_record` where `id`='$recordid' and `uid` = '$member[uid]'");
		if(!$shaidan){
			$this->ajaxReturn(array('status' => 0,'msg' => '该商品您不可晒单!'));
		}
		$shaidanyn=$this->excq("select sd_id from `@#_shaidan` where `sd_shopid`='$shaidan[shopid]' and `sd_type`='0' and `sd_userid` = '$member[uid]'");
		if($shaidanyn){
			$this->ajaxReturn(array('status' => 0,'msg' => '不可重复晒单!'));
		}
		$ginfo=$this->excq("select id,sid,qishu from `@#_shoplist` where `id`='$shaidan[shopid]' LIMIT 1");
		if(!$ginfo){
			$this->ajaxReturn(array('status' => 0,'msg' => '该商品已不存在!'));
		}
		
		if(isset($_POST['submit'])){
			if(empty($_POST['title'])){
				$this->ajaxReturn(array('status' => 0,'msg' => '标题不能为空'),'json');
			}
			if(empty($_POST['content'])){
				$this->ajaxReturn(array('status' => 0,'msg' => '内容不能为空'),'json');
			}
			$pic = '';
			if (isset($_POST['fileurl_tmp'])){
				foreach ($_POST['fileurl_tmp'] as $key => $value) {
					$pic .= $value.';';
				}
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '请至少上传1张晒单照片！'),'json');
			}
			
			$sd_userid = $this->userinfo['uid'];
			$sd_shopid = $ginfo['id'];
			$sd_shopsid = $ginfo['sid'];
			$sd_qishu = $ginfo['qishu'];
			$sd_title = _htmtocode($_POST['title']);
			
			if(empty($_POST['shaitu'])){
				$sd_thumbs = $_POST['fileurl_tmp'][0];
			}else{
				$sd_thumbs = _htmtocode($_POST['shaitu']);
			}
			
			$sd_content = _htmtocode($_POST['content']);
			$sd_photolist= $pic;
			$sd_time=time();
			$sd_ip = _get_ip_dizhi();
			$this->aud("INSERT INTO `@#_shaidan`(`sd_userid`,`sd_shopid`,`sd_shopsid`,`sd_qishu`,`sd_ip`,`sd_title`,`sd_thumbs`,`sd_content`,`sd_photolist`,`sd_time`)VALUES
					('$sd_userid','$sd_shopid','$sd_shopsid','$sd_qishu','$sd_ip','$sd_title','$sd_thumbs','$sd_content','$sd_photolist','$sd_time')");
	
			$this->ajaxReturn(array('status' => 1,'msg' => '晒单分享成功'),'json');
		}
		
		$this->ajaxReturn(array('status' => 1,'shopinfo' => $ginfo));
	}
	
	//晒单列表
	private function shaidan(){
		$parm= I('get.type');
		$p= I('get.p',1,'intval');
		//分页
		$end=10;
		$star=($p-1)*$end;
		
		if($parm=='new'){
			$sel='`sd_time`';
		}else if($parm=='renqi'){
			$sel='`sd_zhan`';
		}else if($parm=='pinglun'){
			$sel='`sd_ping`';
		}
		$count= $this->excq("select * from `@#_shaidan` order by $sel DESC",2);
		$shaidan=$this->excq("select * from `@#_shaidan` order by $sel DESC limit $star,$end",2);
		
		foreach($shaidan as $sd){
			$user[]=get_user_name($sd['sd_userid']);
			$time[]=date("Y-m-d H:i",$sd['sd_time']);
			$member=$this->excq("select * from `@#_member` where `uid`='$sd[sd_userid]'",1);
			$pic[]=$member['img'];
		}
		
		for($i=0;$i<count($shaidan);$i++){
			$shaidan[$i]['user']=$user[$i];
			$shaidan[$i]['time']=$time[$i];
			$shaidan[$i]['pic']=$pic[$i];
		}
		$pagex=ceil(count($count)/$end);
		if($p<=$pagex){
			$shaidan[0]['page']=$p+1;
		}
		if($pagex>0){
			$shaidan[0]['sum']=$pagex;
		}else if($pagex==0){
			$shaidan[0]['sum']=$pagex;
		}
		//echo json_encode($shaidan);
		$this->ajaxReturn($shaidan);
	}
	
	//提交晒单评论
	private function plajax(){
		$this->getUserinfo();
		$member=$this->userinfo;
		$sdhf_id= I('post.sd_id',0,'intval');
		$sdhf_userid=$member['uid'];
		$sdhf_content= I('post.content');
		$sdhf_time=time();
		if($sdhf_content==null || !$sdhf_id){
			$this->ajaxReturn(array('status' => 0,'msg' => '评论内容不能为空'),'json');
		}
		$shaidan= $this->excq("select * from `@#_shaidan` where `sd_id`='$sdhf_id'");
		$this->aud("INSERT INTO `@#_shaidan_hueifu`(`sdhf_id`,`sdhf_userid`,`sdhf_content`,`sdhf_time`) VALUES ('$sdhf_id','$sdhf_userid','$sdhf_content','$sdhf_time')");
		$sd_ping=$shaidan['sd_ping']+1;
		$this->aud("UPDATE `@#_shaidan` SET sd_ping='$sd_ping' where sd_id='$shaidan[sd_id]'");
		
		$data = array(
			'u_thumb' => get_user_key($sdhf_userid),
			'u_username' => userid($sdhf_userid),
			'sdhf_time' => date('Y-m-d H:i:s',$sdhf_time),
			'sdhf_userid' => $sdhf_userid,
			'sdhf_content' => $sdhf_content
		);
		
		$this->ajaxReturn(array('status' => 1,'data' => $data,'count' => $sd_ping,'msg' => 'ok'),'json');
	}
	
	//羡慕嫉妒恨
	private function xianmu(){
		$this->getUserinfo('jsonp');
		$sd_id= I('get.id',0,'intval');
		if (!$sd_id) $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'));
		if (M('shaidan_zhan')->where(array('sd_id' => $sd_id,'uid' => $this->userinfo['uid']))->find()){
			$this->ajaxReturn(array('status' => 0,'msg' => '已赞'));
		}
		if (isset($_GET['openstatus'])){
			return;
		}
		if (M('shaidan')->where(array('sd_id' => $sd_id))->setInc('sd_zhan',1)){
			$data = array(
				'uid' => $this->userinfo['uid'],
				'sd_id' => $sd_id,
				'addtime' => time()
			);
			M('shaidan_zhan')->add($data);
			$count = M('shaidan')->where(array('sd_id' => $sd_id))->getField('sd_zhan');
			$this->ajaxReturn(array('status' => 1,'count' => $count,'msg' => 'ok'));
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => 'error'));
		}
	}
	
	//访问他人购买记录
	private function getuserbuylist(){
		if (!($uid = intval($_GET['uid']))){
			$this->ajaxReturn(array('status' => 0,'msg' => '用户不存在'));
		}
		$this->userinfo = M('member')->where(array('uid' => $uid))->find();
		if (empty($this->userinfo)) $this->ajaxReturn(array('status' => 0,'msg' => '用户不存在'));
		$type=$_GET['type'];
		$uid=$this->userinfo['uid'];
		$FIdx=$_GET['start'];
		$EIdx=10;//$this->segment(7);
		$isCount= $_GET['iscount'];
	
		if($type==0){
			//参与购买的商品 全部...
			$shoplist=$this->excq("select *,sum(gonumber) as gonumber from `@#_member_go_record` a left join `@#_shoplist` b on a.shopid=b.id where a.uid='$uid' and b.isFree=0 GROUP BY shopid",2);
			$shop['listItems']=$this->excq("select *,sum(gonumber) as gonumber from `@#_member_go_record` a left join `@#_shoplist` b on a.shopid=b.id where a.uid='$uid' and b.isFree=0 GROUP BY shopid order by a.time desc limit $FIdx,$EIdx",2);
		}elseif($type==1){
			//获得奖品
			$shoplist= $this->excq("select * from  `@#_shoplist`  where q_uid='$uid' and isFree=0",2);
			$shop['listItems']= $this->excq("select * from  `@#_shoplist`  where q_uid='$uid'  and isFree=0 order by q_end_time desc limit $FIdx,$EIdx",2);
		}elseif($type==2){
			//晒单记录
			$shoplist= $this->excq("select * from `@#_shaidan` a left join `@#_shoplist` b on a.sd_shopid=b.id where a.sd_userid='$uid'",2);
			$shop['listItems']= $this->excq("select * from `@#_shaidan` a left join `@#_shoplist` b on a.sd_shopid=b.id where a.sd_userid='$uid' order by a.sd_time desc limit $FIdx,$EIdx",2);
		}
	
		if(empty($shop['listItems'])){
			$shop['code']=4;
		}else{
			foreach($shop['listItems'] as $key=>$val){
				if($val['q_end_time']!=''){
					$shop['listItems'][$key]['q_open_lottery'] = "javascript:openItem('dataserver',{$val['id']},function(id){localData.set('dataserver_goods_id',id);});";
					$shop['listItems'][$key]['codeState']=3;
					$shop['listItems'][$key]['q_user']=get_user_name($val['q_uid']);
					$shop['listItems'][$key]['q_end_time']=microt($val['q_end_time']);
				}else{
					$shop['listItems'][$key]['q_open_lottery'] = "javascript:openItem('item',{$val['id']},function(id){localData.set('goods_id',id);});";
				}
				if(isset($val['sd_time'])){
					$shop['listItems'][$key]['sd_time']=date('m月d日 H:i',$val['sd_time']);
				}
				
				unset($shop['listItems'][$key]['goucode']);
				unset($shop['listItems'][$key]['q_content']);
			}
			$shop['code']=0;
			$shop['count']=count($shoplist);
		}
		
		$this->ajaxReturn($shop);
		
	}
	
	//访问个人主页
	private function userindex(){
		
		if (!($uid = intval($_GET['userid']))){
			$this->ajaxReturn(array('status' => 0,'用户不存在'));
		}
		
		//获取个人资料
		$member=$this->excq("select * from `@#_member` where `uid`='$uid'");
		if (empty($member)){
			$this->ajaxReturn(array('status' => 0,'用户不存在'));
		}
		
		$member['username'] = get_user_name($member['uid']);
		$this->ajaxReturn(array('status' => 1,'data' => $member));
		//获取购买等级  购买新手  购买小将==
		/*
		$memberdj=$this->excq("select * from `@#_member_group`",2);
		$jingyan=$member['jingyan'];
		if(!empty($memberdj)){
			foreach($memberdj as $key=>$val){
				if($jingyan>=$val['jingyan_start'] && $jingyan<=$val['jingyan_end']){
					$member['yungoudj']=$val['name'];
				}
			}
		}
		*/
		
	}
	
	//结算页面
	private function join_payment(){
		$this->getUserinfo();
		$cartJSON = isset($_POST['json'])?$_POST['json']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
	
		$shoplist=array();
		if($shopids!=NULL){
			$arr = explode(',', $shopids);
			$shoplist=$this->excq("SELECT * FROM `@#_teamgoods` where `id` in($shopids)",3,$arr);
		}
		$MoenyCount=0;
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					$ten_per = floor($shoplist[$key]['zongrenshu']/1) > 0 ? floor($shoplist[$key]['zongrenshu']/1) : 1;
					$max = $ten_per > $shoplist[$key]['cart_shenyu'] ? $shoplist[$key]['cart_shenyu'] : $ten_per;
					if($val['num'] > $max){
						//_messagemobile($shoplist[$key]['title']."购买数量不能大于".$max,WEB_PATH.'/mobile/cart/cartlist');
					}
				}
			}
			$shopnum=0;  //表示有商品
		}else{
			// 			_setcookie('Cartlist',NULL);
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
	
		// 总支付价格
		$MoenyCount = substr( sprintf ( "%.3f", $MoenyCount), 0, - 1 );
		// 会员余额
		$Money = $this->userinfo['money'];
		// 商品数量
		$shoplen = count($shoplist);	
		$paylist = $this->excq("SELECT * FROM `@#_pay` where `pay_start` = '1' AND pay_mobile = 1",2);
		$alipay_key = require_once APP_CORE.'/config/key.inc.php';
		foreach ($paylist as $key => $value){
			$pay_key = unserialize($value['pay_key']);
			if($value['pay_class'] == 'wapalipay'){
				$paylist[$key]['pay_partner'] = $pay_key['id']['val'];
				$paylist[$key]['pay_key'] = $pay_key['key']['val'];
				$paylist[$key]['pay_account'] = $pay_key['user']['val'];
				$paylist[$key]['public_key'] = $alipay_key['alipay']['public_key'];
				$paylist[$key]['private_key'] = $alipay_key['alipay']['private_key'];
			}elseif ($value['pay_class'] == 'wxpay_web'){
				$paylist[$key]['pay_partner'] = $pay_key['APPID']['val'];
				$paylist[$key]['pay_key'] = $pay_key['KEY']['val'];
				$paylist[$key]['pay_account'] = $pay_key['MCHID']['val'];
			}
		}
		$payhtml = '';
		foreach ($paylist as $key => $value) {
			$payhtml .= '<li class="gray9 select_pay" urm="'.$value['pay_id'].'"><i><s></s>';
			$checked = '';
			$css = "";
			if($value['pay_class'] == 'wapalipay'){
				$checked = 'checked="checked"';
				$css = 'class="selectedP"';
			}
			$payhtml .= '<input id="'.$value['pay_id'].'" item="'.$value['pay_class'].'" class="regular-radio" '.$checked.' type="radio" value="'.$value['pay_id'].'" name="account" id="'.$value['pay_class'].'">';
			$payhtml .= '<label for="'.$value['pay_id'].' '.$css.'"></label></i>'.$value['pay_name'].'</li>';
		}
	
		$this->ajaxReturn(array('status' => 1,
				'money' => $Money,
				'hidPoints' => $this->userinfo['score'],
				'count'=> $shoplen,
				'payapi' => $paylist,
				'paylist' => $payhtml,
				'pay_type' => $Money>=$MoenyCount?'ok':'error',
				'shoplist' => $shoplist,
				'MoenyCount' => $MoenyCount),'json');
	
	}
	
	//结算页面
	private function fpayment(){
		$this->getUserinfo($this->jsonp);
		$cartJSON = isset($_POST['json'])?$_POST['json']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
	
		$shoplist=array();
		if($shopids!=NULL){
			$arr = explode(',', $shopids);
			$shoplist=$this->excq("SELECT * FROM `@#_shoplist` where `id` in($shopids)",3,$arr);
		}
		$MoenyCount=0;
		$ALLinvite_num = 0;
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$ALLinvite_num += $shoplist[$key]['freeMin'];
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					$ten_per = floor($shoplist[$key]['zongrenshu']/1) > 0 ? floor($shoplist[$key]['zongrenshu']/1) : 1;
					$max = $ten_per > $shoplist[$key]['cart_shenyu'] ? $shoplist[$key]['cart_shenyu'] : $ten_per;
					if($val['num'] > $max){
						//_messagemobile($shoplist[$key]['title']."购买数量不能大于".$max,WEB_PATH.'/mobile/cart/cartlist');
					}
				}
			}
			$shopnum=0;  //表示有商品
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
	
		// 总支付价格
		$MoenyCount = substr( sprintf ( "%.3f", $MoenyCount), 0, - 1 );
		// 会员余额
		$Money = 0;
		// 商品数量
		$shoplen = count($shoplist);
		$paylist = $this->excq("SELECT * FROM `@#_pay` where `pay_start` = '1' AND pay_mobile = 1",2);
		$alipay_key = require_once APP_CORE.'/config/key.inc.php';

		$this->ajaxReturn(array('status' => 1,
				'money' => $Money,
				'hidPoints' => $this->userinfo['score'],
				'count'=> $shoplen,
				'payapi' => $paylist,
				'pay_type' => $Money>=$MoenyCount?'ok':'error',
				'shoplist' => $shoplist,
				'invite_num' => $this->userinfo['invite_num'],
				'all_inviteNum' => $ALLinvite_num,
				'MoenyCount' => $MoenyCount),'json');
	
	}
	
	//结算页面
	private function payment(){
		$this->getUserinfo();
		$cartJSON = isset($_POST['json'])?$_POST['json']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
		
		$shoplist=array();
		if($shopids!=NULL){
			$arr = explode(',', $shopids);
			$shoplist=$this->excq("SELECT * FROM `@#_shoplist` where `id` in($shopids)",3,$arr);
		}
		$MoenyCount=0;
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
					if(isset($shoplist[$key])){
						$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
						$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
						$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
						$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
						$ten_per = floor($shoplist[$key]['zongrenshu']/1) > 0 ? floor($shoplist[$key]['zongrenshu']/1) : 1;
						$max = $ten_per > $shoplist[$key]['cart_shenyu'] ? $shoplist[$key]['cart_shenyu'] : $ten_per;
						if($val['num'] > $max){
							//_messagemobile($shoplist[$key]['title']."购买数量不能大于".$max,WEB_PATH.'/mobile/cart/cartlist');
						}
						unset($shoplist[$key]['content']);
						unset($shoplist[$key]['picarr']);
					}
			}
			$shopnum=0;  //表示有商品
		}else{
// 			_setcookie('Cartlist',NULL);
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		
		// 总支付价格
		$MoenyCount = substr( sprintf ( "%.3f", $MoenyCount), 0, - 1 );
		// 会员余额
		$Money = $this->userinfo['money'];
		// 商品数量
		$shoplen = count($shoplist);
		
		//使用积分代付
		$fufen = require_once INC_PATH.'/member/lib/user_fufen.ini.php';
		if ($fufen ['fufen_yuan']) {
			$fufen_dikou = intval ($this->userinfo['score'] / $fufen ['fufen_yuan'] );
		} else {
			$fufen_dikou = 0;
		}
		$fufen_dikou = 0;
		
		$paylist = $this->excq("SELECT * FROM `@#_pay` where `pay_start` = '1' AND pay_mobile = 1",2);
		$alipay_key = require_once APP_CORE.'/config/key.inc.php';
		foreach ($paylist as $key => $value){
			$pay_key = unserialize($value['pay_key']);
			if($value['pay_class'] == 'wapalipay'){
				$paylist[$key]['pay_partner'] = $pay_key['id']['val'];
				$paylist[$key]['pay_key'] = $pay_key['key']['val'];
				$paylist[$key]['pay_account'] = $pay_key['user']['val'];
				$paylist[$key]['public_key'] = $alipay_key['alipay']['public_key'];
				$paylist[$key]['private_key'] = $alipay_key['alipay']['private_key'];
			}elseif ($value['pay_class'] == 'wxpay_web'){
				$paylist[$key]['pay_partner'] = $pay_key['APPID']['val'];
				$paylist[$key]['pay_key'] = $pay_key['KEY']['val'];
				$paylist[$key]['pay_account'] = $pay_key['MCHID']['val'];
			}
		}
		$payhtml = '';
		foreach ($paylist as $key => $value) {
			$payhtml .= '<li class="gray9 select_pay" urm="'.$value['pay_id'].'"><i><s></s>';
			$checked = '';
			$css = "";
			if($value['pay_class'] == 'wapalipay'){
				$checked = 'checked="checked"';
				$css = 'class="selectedP"';
			}
			$payhtml .= '<input id="'.$value['pay_id'].'" item="'.$value['pay_class'].'" class="regular-radio" '.$checked.' type="radio" value="'.$value['pay_id'].'" name="account" id="'.$value['pay_class'].'">';
			$payhtml .= '<label for="'.$value['pay_id'].' '.$css.'"></label></i>'.$value['pay_name'].'</li>';
		}
		$pay_type = 'error';
		switch ($MoenyCount){
			//case $fufen_dikou>=$MoenyCount:
			//	$pay_type = 'fufen_dikou';
			//	break;
			case $Money>=$MoenyCount:
				$pay_type = 'money';
				break;
			default:
				break;
		}	
		$this->ajaxReturn(array('status' => 1,
				'money' => $Money,
				'hidPoints' => $this->userinfo['score'],
				'count'=> $shoplen,
				'payapi' => $paylist,
				'paylist' => $payhtml,
				//'pay_type' => $Money>=$MoenyCount?'ok':'error',
				'pay_type' => $pay_type,
				'shoplist' => $shoplist,
				'fufen_dikou' => $fufen_dikou,
				'MoenyCount' => $MoenyCount),'json');
		
	}
	
	//判断是否购物车提交
	private function is_check_postCart(){
		if (!isset($_POST['submit'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '订单提交失败'),'json');
		}
		header ("Cache-control: private" );
		if (!isset($_POST['cart']) || empty($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$this->getUserinfo();
	}
	
	//余额支付
	private function joinpaysubmit() {
		$this->is_check_postCart();
		$checkpay = isset($_POST['checkpay'])?$_POST['checkpay']:''; // 获取支付方式 fufen money bank
		$banktype = isset($_POST['banktype'])?$_POST['banktype']:''; // 获取选择的银行 CMBCHINA ICBC CCB
		$money = isset($_POST['money'])?$_POST['money']:''; // 获取需支付金额
		$fufen = isset($_POST['score'])?$_POST['score']:''; // 获取福分
		$isBag = isset($_POST['bag'])?$_POST['bag']:'a';
		//$submitcode1 = $this->segment (8); // 获取SESSION 做防止重复提交
		$uid = $this->userinfo ['uid'];
		$zhifutype = $this->excq("select * from `@#_pay` where `pay_class` = 'alipay'");
		if (!$zhifutype) {
			$this->ajaxReturn(array('status' => 0,'msg' => '请使用微支付或支付宝'),'json');
		}
		$pay_checkbox = false; //钱包支付
		$pay_type_bank = false; //银行卡支付
		$pay_type_id = false;   //获取平台支付类型，支付宝，微信支付...
		if ($checkpay == 'money') {
			$pay_checkbox = true;
		}
		//不是银行
		if ($banktype != 'nobank') {
			$pay_type_id = $banktype; //支付类型的id
		}
		if (! empty ($zhifutype)) {
			$pay_type_bank = $zhifutype['pay_class'];
		}
		if (!$pay_type_id) {
			if ($checkpay != 'fufen' && $checkpay != 'money'){
				$this->ajaxReturn(array('status' => 0,'msg' => '请使用微支付或支付宝2'),'json');
			}
		}
	
		$pay = new pay();// 购买商品
		$pay->pay_type_str = $isBag;
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$pay->fufen = $checkpay == 'fufen'?$fufen:0;
		$pay->pay_type_bank = $pay_type_bank;
		//提交订单时间，实时检测商品
		$ok = $pay->init($uid,$pay_type_id,'join_go_record');
		if ($ok != 'ok') {
			$this->ajaxReturn(array('status' => 0,'msg' => $ok),'json');
		}
		//以上全检测通过后，进入，支付，生成订单号，生成抢购号
		$check = $pay->join_go_pay($pay_checkbox);
		if (!$check){
			$this->ajaxReturn(array('status' => 0,'msg' => '订单添加失败'),'json');
		}
		if ($check) {
			// 成功
			$this->ajaxReturn(array('status' => 1,'msg' => '购买成功'),'json');
		} else {
			// 失败
			$this->ajaxReturn(array('status' => 0,'msg' => '订单添加失败'),'json');
		}
	}
	
	//余额支付
	private function paysubmit() {
		$this->is_check_postCart();
		$checkpay = isset($_POST['checkpay'])?$_POST['checkpay']:''; // 获取支付方式 fufen money bank
		$banktype = isset($_POST['banktype'])?$_POST['banktype']:''; // 获取选择的银行 CMBCHINA ICBC CCB
		$money = isset($_POST['money'])?$_POST['money']:0; // 获取需支付金额
		$fufen = isset($_POST['score'])?$_POST['score']:0; // 获取福分
		$isBag = isset($_POST['bag'])?$_POST['bag']:'a';
		//$submitcode1 = $this->segment (8); // 获取SESSION 做防止重复提交
		$uid = $this->userinfo ['uid'];
		$zhifutype = $this->excq("select * from `@#_pay` where `pay_class` = 'alipay'");
		if (!$zhifutype) {
			$this->ajaxReturn(array('status' => 0,'msg' => '请使用微支付或支付宝'),'json');
		}
		$pay_checkbox = false; //钱包支付
		$pay_type_bank = false; //银行卡支付
		$pay_type_id = false;   //获取平台支付类型，支付宝，微信支付...
		if ($checkpay == 'money') {
			$pay_checkbox = true;
		}
		//不是银行
		if ($banktype != 'nobank') {
			$pay_type_id = $banktype; //支付类型的id
		}
		if (! empty ($zhifutype)) {
			$pay_type_bank = $zhifutype['pay_class'];
		}
		if (!$pay_type_id) {
			if ($checkpay != 'fufen' && $checkpay != 'money'){
				$this->ajaxReturn(array('status' => 0,'msg' => '请使用微支付或支付宝2'),'json');
			}
		}
		
		$pay = new pay();// 购买商品
		$pay->pay_type_str = $isBag;
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$pay->fufen = $checkpay == 'fufen'?$fufen:0;
		$pay->pay_type_bank = $pay_type_bank;
		//提交订单时间，实时检测商品
		$ok = $pay->init($uid,$pay_type_id,'go_record');
		if ($ok != 'ok') {
			$this->ajaxReturn(array('status' => 0,'msg' => $ok),'json');
		}
		//以上全检测通过后，进入，支付，生成订单号，生成抢购号
		$check = $pay->go_pay($pay_checkbox);
		if ($check) {
			// 成功
			$this->ajaxReturn(array('status' => 1,'msg' => '购买成功'),'json');
		} else {
			// 失败
			$this->ajaxReturn(array('status' => 0,'msg' => '订单添加失败'),'json');
		}
	}
	
	//提交订单成功并充值成功，继续付款
	private function joingopayment(){
		$this->is_check_postCart();
		if (empty($_POST['code']) || empty($_POST['money']) || $_POST['money'] <= 0){
			$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
		}
		$pay_type = '支付宝';
		if($_POST['pay_type'] == 'wapalipay'){
			$pay_type = '支付宝';
		}elseif ($_POST['pay_type'] == 'wxpay_web'){
			$pay_type = '微支付';
		}
	
		if(!isset($_POST['pay_type'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '请选择支付平台'),'json');
		}
		$fufen = isset($_POST['score'])?$_POST['score']:''; // 获取福分
		$pay = new pay();// 购买商品
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$pay->fufen = 0;
		$pay->pay_type_bank = $_POST['pay_type'];
		//提交订单时间，实时检测商品
		$ok = $pay->init($this->userinfo['uid'],0,'join_go_record');
		if ($ok != 'ok'){
			$this->ajaxReturn(array('status' => 0,'msg' => $ok),'json');
		}else{
			$data = array(
					'code' => I('post.code'),
					'money' => I('post.money'),
					'pay_type' => $pay_type,
					'status' => '未付款',
					'uid' => $this->userinfo['uid'],
					'time' => NOW_TIME,
					'score' => 0,
					'scookies' => $_POST['cart'],
			);
			if (!M('member_addmoney_record')->add($data)){
				$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
			}
			$this->ajaxReturn(array('status' => 1,'msg' => 'ok'),'json');
		}
	}
	
	//提交订单成功并充值成功，继续付款
	private function gopayment(){
		$this->is_check_postCart();
		if (empty($_POST['code']) || empty($_POST['money']) || $_POST['money'] <= 0){
			$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
		}
		$pay_type = '支付宝';
		if($_POST['pay_type'] == 'wapalipay'){
			$pay_type = '支付宝';
		}elseif ($_POST['pay_type'] == 'wxpay_web'){
			$pay_type = '微支付';
		}
		
		if(!isset($_POST['pay_type'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '请选择支付平台'),'json');
		}
		$fufen = isset($_POST['score'])?$_POST['score']:''; // 获取福分
		$pay = new pay();// 购买商品
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$pay->fufen = 0;
		$pay->pay_type_bank = $_POST['pay_type'];
		//提交订单时间，实时检测商品
		$ok = $pay->init($this->userinfo['uid'],0,'go_record');
		if ($ok != 'ok'){
			$this->ajaxReturn(array('status' => 0,'msg' => $ok),'json');
		}else{
			$data = array(
					'code' => I('post.code'),
					'money' => I('post.money'),
					'pay_type' => $pay_type,
					'status' => '未付款',
					'uid' => $this->userinfo['uid'],
					'time' => NOW_TIME,
					'score' => 0,
					'scookies' => $_POST['cart'],
			);
			if (!M('member_addmoney_record')->add($data)){
				$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
			}
			$this->ajaxReturn(array('status' => 1,'msg' => 'ok'),'json');
		}
	}
	
	//提交订单成功并充值成功，继续付款
	private function teamgopayment(){
		$this->is_check_postCart();
		if (empty($_POST['code']) || empty($_POST['money']) || $_POST['money'] <= 0){
			$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
		}
		$pay_type = '支付宝';
		if($_POST['pay_type'] == 'wapalipay'){
			$pay_type = '支付宝';
		}elseif ($_POST['pay_type'] == 'wxpay_web'){
			$pay_type = '微支付';
		}
		if(!isset($_POST['pay_type'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '请选择支付平台'),'json');
		}
		$fufen = isset($_POST['score'])?$_POST['score']:''; // 获取福分
		$pay = new pay();// 购买商品
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		$pay->fufen = 0;
		$pay->pay_type_bank = $_POST['pay_type'];
		//提交订单时间，实时检测商品
		$ok = $pay->init($this->userinfo['uid'],0,'check_goods');
		if ($ok != 'ok'){
			$this->ajaxReturn(array('status' => 0,'msg' => $ok),'json');
		}else{
			$data = array(
					'code' => I('post.code'),
					'money' => I('post.money'),
					'pay_type' => $pay_type,
					'status' => '未付款',
					'uid' => $this->userinfo['uid'],
					'time' => NOW_TIME,
					'score' => 0,
					'scookies' => $_POST['cart'],
			);
			if (!M('member_addmoney_record')->add($data)){
				$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
			}
			$this->ajaxReturn(array('status' => 1,'msg' => 'ok'),'json');
		}
	}
	
	//购物车商品列表
	private function join_cartlist(){
		$cartJSON = isset($_POST['cart'])?$_POST['cart']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
	
		$shoplist=array();
		if($shopids!=NULL){
			$shoparr=$this->model->query("SELECT * FROM `".C('DB_PREFIX')."teamgoods` where `id` in($shopids)",array("key"=>"id"));
		}
		if(!empty($shoparr)){
			foreach($shoparr as $key=>$val){
				if($val['q_end_time']=='' || $val['q_end_time']==NULL){
					$shoplist[$val['id']]=$val;
					$Mcartlist[$val['id']]['num']=$Mcartlist[$val['id']]['num'];
					$Mcartlist[$val['id']]['shenyu']=$val['shenyurenshu'];
					$Mcartlist[$val['id']]['money']=$val['yunjiage'];
				}
			}
		}
		$MoenyCount=0;
		//$Cartshopinfo='{';
		$_temp = array();
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					//$Cartshopinfo.="'$key':{'shenyu':".$shoplist[$key]['cart_shenyu'].",'num':".$val['num'].",'money':".$shoplist[$key]['yunjiage']."},";
					$_temp[$key] = array(
							"shenyu" => $shoplist[$key]['cart_shenyu'],
							"num" => $val['num'],
							"money" => $shoplist[$key]['yunjiage']
					);
				}
			}
		}
	
		$shop=0;
		if(!empty($shoplist)){
			$shop=1;
		}
		$MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
		//$Cartshopinfo.="'MoenyCount':$MoenyCount}";
		$this->ajaxReturn(array('shop' => $shop,'shoplist' => $shoplist,'cartinfo' => $_temp,'MoenyCount' => $MoenyCount),'json');
	}
	
	private function cartHandler(){
		$cartJSON = isset($_POST['cart'])?$_POST['cart']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
		
		$shoplist=array();
		if($shopids!=NULL){
			$shoparr=$this->model->query("SELECT * FROM `".C('DB_PREFIX')."shoplist` where `id` in($shopids)",array("key"=>"id"));
		}
		if(!empty($shoparr)){
			foreach($shoparr as $key=>$val){
				if($val['q_end_time']=='' || $val['q_end_time']==NULL){
					$shoplist[$val['id']]=$val;
					$Mcartlist[$val['id']]['num']=$Mcartlist[$val['id']]['num'];
					$Mcartlist[$val['id']]['shenyu']=$val['shenyurenshu'];
					$Mcartlist[$val['id']]['money']=$val['yunjiage'];
				}
			}
		}
		$MoenyCount=0;
		//$Cartshopinfo='{';
		$_temp = array();
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					//$Cartshopinfo.="'$key':{'shenyu':".$shoplist[$key]['cart_shenyu'].",'num':".$val['num'].",'money':".$shoplist[$key]['yunjiage']."},";
					$_temp[$key] = array(
							"shenyu" => $shoplist[$key]['cart_shenyu'],
							"num" => $val['num'],
							"money" => $shoplist[$key]['yunjiage']
					);
				}
			}
		}
		
		return array(
			'shoplist' => $shoplist,
			'temp' => $_temp,
			'MoenyCount' => $MoenyCount
		);
	}
	
	//购物车商品列表
	private function f_cartlist(){
		$cartMap = $this->cartHandler();
		$this->getUserinfo($this->jsonp);
		$shop=0;
		if(!empty($cartMap['shoplist'])){
			$shop=1;
			$model = M('member_go_record');
			foreach ($cartMap['shoplist'] as $key => $value){
				$where = array('shopid' => $value['id'],'uid' => $this->userinfo['uid']);
				$gonumber = $model->where($where)->sum('gonumber');
				$cartMap['shoplist'][$key]['freeMax'] = $value['freeMax']-$gonumber;
			}
		}
		$MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
		$this->ajaxReturn(array('shop' => $shop,'shoplist' => $cartMap['shoplist'],'cartinfo' => $cartMap['temp'],'MoenyCount' => $cartMap['MoenyCount']),'json');
	}
	
	//余额支付
	private function fpaysubmit() {
		$this->is_check_postCart();
		//$submitcode1 = $this->segment (8); // 获取SESSION 做防止重复提交
		$uid = $this->userinfo ['uid'];
		$pay = new pay();// 购买商品
		$pay->pay_type_str = 'a';
		if(!$pay->setcart($_POST['cart'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '购物车没有商品'),'json');
		}
		//提交订单时间，实时检测商品
		$result = $pay->init($uid,1,'f_go_record');
		if ($result === true){
			$this->ajaxReturn(array('status' => 1,'msg' => '购买成功'),'json');
		}elseif ($result === false){
			$this->ajaxReturn(array('status' => 0,'msg' => '订单添加失败'),'json');
		}elseif (is_string($result)){
			$this->ajaxReturn(array('status' => 0,'msg' => $result),'json');
		}
	}
	
	//购物车商品列表
	private function cartlist(){
		$cartJSON = isset($_POST['cart'])?$_POST['cart']:'';
		$Mcartlist=json_decode($cartJSON,true);
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');	
		}

		$shoplist=array();
		if($shopids!=NULL){
			$shoparr=$this->model->query("SELECT * FROM `".C('DB_PREFIX')."shoplist` where `id` in($shopids)",array("key"=>"id"));
		}
		if(!empty($shoparr)){
			foreach($shoparr as $key=>$val){
				if($val['q_end_time']=='' || $val['q_end_time']==NULL){
					$shoplist[$val['id']]=$val;
					$Mcartlist[$val['id']]['num']=$Mcartlist[$val['id']]['num'];
					$Mcartlist[$val['id']]['shenyu']=$val['shenyurenshu'];
					$Mcartlist[$val['id']]['money']=$val['yunjiage'];
				}
			}
		}
		$MoenyCount=0;
		//$Cartshopinfo='{';
		$_temp = array();
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					//$Cartshopinfo.="'$key':{'shenyu':".$shoplist[$key]['cart_shenyu'].",'num':".$val['num'].",'money':".$shoplist[$key]['yunjiage']."},";
					$_temp[$key] = array(
						"shenyu" => $shoplist[$key]['cart_shenyu'],
						"num" => $val['num'],
						"money" => $shoplist[$key]['yunjiage']
					);
				}
			}
		}
	
		$shop=0;
		if(!empty($shoplist)){
			$shop=1;
		}
		$MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
		//$Cartshopinfo.="'MoenyCount':$MoenyCount}";
		$this->ajaxReturn(array('shop' => $shop,'shoplist' => $shoplist,'cartinfo' => $_temp,'MoenyCount' => $MoenyCount),'json');		
	}
	
	//删除取消充值订单
	private function removeorder(){
		$this->getUserinfo('jsonp');
		if (isset($_GET['sncode']) && !empty($_GET['sncode'])){
			$where = array('uid' => $this->userinfo['uid'],'code' => $_GET['sncode']);
			if (M('member_addmoney_record')->where($where)->delete()){
				$this->ajaxReturn(array('status' => 1,'msg' => '删除成功'));
			}else{
				//
			}
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '非法操作'));
		}
	}
	
	//最新揭晓
	private function lottery(){
		//$FIdx=0;
		//$EIdx=10;
		$page = I('page',1,'intval');
		$isCount=1;
		$total= $this->model->query("select COUNT(*) as c from `".C('DB_PREFIX')."shoplist` where `q_uid` is not null and `q_showtime` = 'N'");
		$total = current($total)['c'];
		$getLimit = $this->getLimit($total,$page,10);
		$totalPage = $getLimit['totalPage'];
		//最新揭晓
		$shoplist['listItems']= $this->model->query("select * from `".C('DB_PREFIX')."shoplist` where `q_uid` is not null and `q_showtime` = 'N' ORDER BY `q_end_time` DESC {$getLimit['limit']}");
		if(empty($shoplist['listItems'])){
			$shoplist['code']=1;
		}else{
			$model = M('member_go_record');
			foreach($shoplist['listItems'] as $key=>$val){
				//查询出购买次数
				/*
				$recodeinfo=$this->model->query("select `gonumber` from `".C('DB_PREFIX')."member_go_record` where `uid` ='$val[q_uid]' and `shopid`='$val[id]' and `goucode` like '%{$val['q_user_code']}%' limit 1");
				$recodeinfo = current($recodeinfo);*/
				$gonumber = $model->where(array('uid' => $val['q_uid'],'shopid' => $val['id']))->sum('gonumber');
				$shoplist['listItems'][$key]['q_user']=get_user_name($val['q_uid']);
				$shoplist['listItems'][$key]['userphoto']=get_user_key($val['q_uid'],'img');
				$shoplist['listItems'][$key]['q_end_time']=microt($val['q_end_time']);
				$shoplist['listItems'][$key]['gonumber']=$gonumber;
			}
			$shoplist['code']=0;
			$shoplist['count']=$total;
			$shoplist['totalPage'] = $totalPage;
		}
		
		$this->ajaxReturn($shoplist);
	}

	
	//个人中心创团商品详情
	private function createteam(){
		$this->getUserinfo('jsonp');
		$goods_id = isset($_GET['team_goods_id'])?intval($_GET['team_goods_id']):'';
		if (!$goods_id) $this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		$goods = M('teamgoods')->where(array('id' => $goods_id,'q_create_uid' => $this->userinfo['uid']))->find();
		if (!empty($goods)){
			$goods_order = M('member_team_record')->where(array('uid' => $this->userinfo['uid'],'shopid' => $goods['id']))->find();
			if ($goods_order){
				$goods_order['goucode'] = yunma($goods_order['goucode']);
			}
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '商品不存在'));
		}
		$goods['url'] = W_WEB_PATH.'/tm/'.$goods['id'];
		$lottery = 'no';
		if ($goods['q_uid'] && $goods['q_showtime'] == 'N'){
			$lottery = 'yes';
		}
		$goods['lottery'] = $lottery;
		$goods['share_desc'] = $goods['description']?$goods['description']:$goods['title2'];
		$goods['share_link'] = $goods['url'].'/'._encrypt($this->userinfo['uid']);
		$goods_order['time'] = date('Y-m-d H:i:s',$goods_order['time']);
		$this->ajaxReturn(array('status' => 1,'shopinfo' => $goods,'data' => $goods_order));
	}
	
	//消费记录
	private function getuserconsumption(){
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		$FIdx=intval($_GET['FIdx']);
		$EIdx=100;
		
		$memberAccount = M('member_account');
		$where = array('uid' => $member['uid'],'pay' => '账户','type' => '-1');
		$Consumptionlist = $memberAccount->where($where)->count();
		$limit = $FIdx.','.$EIdx;
		$Consumption['listItems'] = $memberAccount->where($where)->order('time desc')->limit($limit)->select();
		if(empty($Consumption['listItems'])){
			$Consumption['code'] = 1;
		}else{
			foreach($Consumption['listItems'] as $key=>$val){
				$Consumption['listItems'][$key]['time']=date("Y-m-d H:i:s",$val['time']);
			}
			$Consumption['code']=0;
		}
		
		$Consumption['count']= $Consumptionlist;
		
		$this->ajaxReturn($Consumption);
	
	}
	
	//获取支付接口
	private function get_payapi(){
		$this->getUserinfo('jsonp');
		$paylist = $this->model->query("SELECT * FROM `".C('DB_PREFIX')."pay` where `pay_start` = '1' AND pay_mobile = 1");
		$data = array('status' => 1,'money' => $this->userinfo['money'],'paylist' => $paylist);
		$this->ajaxReturn($data);
	}
	
	//充值
	private function recharge(){
		$this->getUserinfo();
		if (empty($_POST['code']) || empty($_POST['money']) || $_POST['money'] <= 0){
			$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
		}
		$data = array(
			'code' => I('post.code'),
			'money' => I('post.money'),
			'pay_type' => I('post.pay_type'),
			'status' => '未付款',
			'uid' => $this->userinfo['uid'],
			'time' => NOW_TIME,
			'score' => 0,
			'scookies' => 0,
		);
		if (M('member_addmoney_record')->add($data)){
			$this->ajaxReturn(array('status' => 1,'msg' => '提交成功'),'json');
		}else{
			$this->ajaxReturn(array('status' => 0,'msg' => '提交失败'),'json');
		}
	}
	
	//充值记录
	private function getuserrecharge(){
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		$FIdx= intval($_GET['FIdx']);
		$EIdx= 100;
		$memberAccount = M('member_account');
		$where = array('uid' => $member['uid'],'pay' => '账户','type' => '1');
		$Rechargelist = $memberAccount->where($where)->count();
		
		$limit = $FIdx.','.$EIdx;
		
		$Recharge['listItems'] = $memberAccount->where($where)->order('time desc')->limit($limit)->select();
	
		if(empty($Recharge['listItems'])){
			$Recharge['code']=1;
		}else{
			foreach($Recharge['listItems'] as $key=>$val){
				$Recharge['listItems'][$key]['time']=date("Y-m-d H:i:s",$val['time']);
			}
			$Recharge['code']=0;
		}
		$Recharge['count']=$Rechargelist;
	
		$this->ajaxReturn($Recharge);
	
	}
	
	//获取一条收货地址
	private function getoneaddress(){
		$this->getUserinfo('jsonp');
		$uid = $this->uid;
		$id = I('get.id',0,'intval');
		if (!$id || !$uid){
			$this->ajaxReturn(array('status' => 0,'msg' => '获取地址失败'));
		}else{
			$data = M('member_dizhi')->where(array('id' => $id,'uid' => $uid))->find();
			if ($data){
				$data['status'] = 1;
				$this->ajaxReturn($data);
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '地址不存在'));
			}
		}
	}
	
	//删除地址
	private function deleteaddress(){
		$this->getUserinfo('jsonp');
		$uid = $this->uid;
		$id = I('get.id',0,'intval');
		if (!$id || !$uid){
			$this->ajaxReturn(array('status' => 0,'msg' => '删除失败'));
		}else{
			$model = M('member_dizhi');
			$qu = $model->where(array('id' => $id))->delete();
			if ($qu){
				$this->ajaxReturn(array('status' => 1,'msg' => '删除成功'));
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '删除失败'));
			}
		}
	}
	
	//点击设置默认地址
	private function setaddressdefault(){
		$this->getUserinfo('jsonp');
		$uid = $this->uid;
		$id = I('get.id',0,'intval');
		if (!$id || !$uid){
			$this->ajaxReturn(array('status' => 0,'msg' => '更新失败'));
		}else{
			$model = M('member_dizhi');
			$model->where(array('uid' => $uid))->setField('default','N');
			$qu = $model->where(array('id' => $id))->setField('default','Y');
			if ($qu){
				$this->ajaxReturn(array('status' => 1,'msg' => '更新成功'));
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '更新失败'));
			}
		}
	}
	
	//账户明细
	private function userbalance(){
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		$account = M('member_account')->where(array('uid' => $member['uid'],'pay' => '账户'))->order('time desc')->select();
		$czsum=0; //充值
		$xfsum=0; //消费
		if(!empty($account)){
			foreach($account as $key=>$val){
				if($val['type']==1){
					$czsum+=$val['money'];
				}else{
					$xfsum+=$val['money'];
				}
			}
		}
		$this->ajaxReturn(array('czsum' => $czsum,'xfsum' => $xfsum,'money' => $member['money']));
	}
	
	//app登录
	private function appuserlogin(){
		$arr = array(
				'username' => $_REQUEST['username'],
				'password' => $_REQUEST['password'],
		);
		$username=safe_replace($arr['username']);
		$pwd = base64_decode($arr['password']);
		$password=md5($pwd);
		$logintype='';
		if(strpos($username,'@')==false){
			//手机
			$logintype='mobile';
		}else{
			//邮箱
			$logintype='email';
		}
			
		$member= $this->model->query("select * from `".C('DB_PREFIX')."member` where `$logintype`='$username' and `password`='$password'");
		
		if (!empty($member)){
			$member = current($member);
		}
		
		if(!$member){
			//帐号不存在错误
			$user['state']=1;
			$user['num']=-2;
			$this->ajaxReturn($user);
			exit;
		}

		if($member[$logintype.'code'] != 1){
			$user['state']=2; //未验证
			$this->ajaxReturn($user);
			exit;
		}
			
		if(!is_array($member)){
			//帐号或密码错误
			$user['state']=1;
			$user['num']=-1;
		}else{
			$member['type_agent'] = 'no';
			if($member['type'] && $member['is_check'] == 2){
				$member['level_name'] = M('agent_level')->where(array('id' => $member['level_id']))->getField('name');
				$member['type_agent'] = 'yes';
			}
			//登录成功
			$user['state']=0;
			$user['uid'] = _encrypt($member['uid']);
			$user['username'] = $member['username'];
			$user['email'] = $member['email'];
			$user['mobile'] = $member['mobile'];
			$user['qianming'] = $member['qianming'];
			$user['money'] = $member['money'];
			$user['score'] = $member['score'];
			$user['face'] = $member['img'];
			$user['type_agent'] = $member['type_agent'];
			$user['ushell'] = _encrypt(md5($member['uid'].$member['password'].$member['mobile'].$member['email']));
		}
		$this->ajaxReturn($user);
	}
	
	//晒单评论
	private function goodspost(){
		$title="晒单评论";
		$itemid=I('itemid',0,'intval');
		$shoplist=$this->excq("select * from `@#_shoplist` where `sid`='$itemid'",2);
		if(!$shoplist){
			//_messagemobile('页面错误!');
			$this->ajaxReturn(array('status' => 0),$this->jsonp);
		}
		$shop='';
		foreach($shoplist as $list){
			$shop.=$list['id'].',';
		}
		$id=trim($shop,',');
		if($id){
			$shaidan=$this->excq("select * from `@#_shaidan` where `sd_shopid` IN ($id) order by `sd_id` DESC",2);
			$sum=0;
			foreach($shaidan as $key=>$sd){
				$shaidan_hueifu=$this->excq("select * from `@#_shaidan_hueifu` where `sdhf_id`='$sd[sd_id]'",2);
				$sum=$sum+count($shaidan_hueifu);
				$shaidan[$key]['sd_userImg'] = G_WEB_PATH.'/'.get_user_key($sd['sd_userid'],'img');
				$shaidan[$key]['sd_time'] = date('Y-m-d H:i:s',$sd['sd_time']);
				$shaidan[$key]['sd_username'] = userid($sd['sd_userid'],'username');
				$qs=$this->excq("select qishu from `@#_shoplist` where `id`='$sd[sd_shopid]'");
				$shaidan[$key]['shoplist'] = $qs;
				$p=trim($sd['sd_photolist'],";");
				$img=explode(';',$p);
				$imgHtml = '';
				foreach($img as $i){
					if($i){
						$imgHtml .='<img src="'.G_WEB_PATH.'/'.$i.'">';
					}
				}
				$shaidan[$key]['maxImg'] = $imgHtml;
			}
		}else{
			$shaidan=0;
			$sum=0;
		}

		$this->ajaxReturn(array('status' => 1,
				'count' => count($shaidan),
				'sum' => $sum,'data' => $shaidan),$this->jsonp);
	}
	
	//搜索商品
	private function search(){
		if(isset($_POST['search'])){
			$keywords = search_replace(I('keywords'));
			$where = array('shenyurenshu' => array('GT',0),'isFree' => 0,'q_uid' => array('EXP','is null'),'title' => array('LIKE','%'.$keywords.'%'));
			$goods_list = M('shoplist')->where($where)
			->field(array($this->field))->select();
			$result = array('status' => 1,'data' => $goods_list);
			/*
			$cookie_history = array();
			if (isset($_COOKIE['history_search']) && !empty($_COOKIE['history_search'])){
				$cookie = unserialize(stripslashes($_COOKIE['history_search']));
				$cookie[] = $keywords;
				$data = array_unique($cookie);
				$this->__setCookie($data);
			}else{
				$cookie_history[] = $keywords;
				$this->__setCookie($cookie_history);
			}
			$history = $this->getCookieHistory();
			$result['html'] = $history['status'] == 1 ? $history['html'] : '';
			*/
			$this->ajaxReturn($result,'json');
		}else{
			//$this->ajaxReturn($this->getCookieHistory());
		}
	}
	
	//获取cookie历史记录
	private function getCookieHistory(){
		if (isset($_COOKIE['history_search'])){
			$cookie_history = $_COOKIE['history_search'];
			$cookie_history = unserialize(stripslashes($cookie_history));
			$html = '';
			foreach ($cookie_history as $key => $value) {
				$html .= '<a href="javascript:;" item="'.$value.'" class="click-history-search">'.$value.'</a>';
			}
			return array('status' => 1,'html' => $html);
		}else{
			return array('status' => 0,'msg' => '没有历史记录');
		}
	}
	
	//清除搜索商品记录
	private function clearhistory(){
		setcookie('history_search',null,-time());
		echo 1;
	}
	
	//设置搜索商品关键词记录
	private function __setCookie($data){
		setcookie('history_search',serialize($data),time()+60*60*24*7);
	}
	
	//app个人中心更新动态部分数据
	private function updateuser(){
		$this->getUserinfo('jsonp');
		$this->ajaxReturn(array('status' => 1,'data' => $this->userinfo));
	}

	//app获取商品列表
	private function appgoodsList(){
		$cate_band = htmlspecialchars(I('show')); //列表方式，
		$select =htmlspecialchars(I('sort')); //排序
		$p = htmlspecialchars(I('page')) ? intval(I('page')) :1; //分页数
		if(!$select){
			$select = '10';
		}
		$fen1 = '';
		if($cate_band){
			$fen1 = intval($cate_band);
			$cate_band = 'list';
		}
	
		$sun_id_str = "'".$fen1."'";
		if($fen1){
			$sun_cate = $this->model->query("SELECT cateid from `".C('DB_PREFIX')."category` where `parentid` = '$fen1'");
			foreach($sun_cate as $v){
				$sun_id_str .= ","."'".$v['cateid']."'";
			}
		}
	
		if(empty($fen1)){
			$brand= $this->model->query("select * from `".C('DB_PREFIX')."brand` where 1 order by `order` DESC");
			$daohang = '所有分类';
		}else{
			$brand= $this->model->query("select * from `".C('DB_PREFIX')."brand` where `cateid` in ($sun_id_str) order by `order` DESC");
			$daohang= $this->excq("select * from `".C('DB_PREFIX')."category` where `cateid` = '$fen1' order by `order` DESC");
			$daohang = $daohang['name'];
		}
	
		$category= $this->model->query("select * from `".C('DB_PREFIX')."category` where `model` = '1'");
	
		//分页
	
		$end=10;
		$star=($p-1)*$end;
	
		$select_w = '';
		if($select == 10){
			$select_w = 'order by `shenyurenshu` ASC';
		}
		if($select == 20){
			$select_w = "and `renqi` = '1'";
		}
		if($select == 30){
			$select_w = 'order by `shenyurenshu` ASC';
		}
		if($select == 40){
			$select_w = 'order by `time` DESC';
		}
		if($select == 50){
			$select_w = 'order by `money` DESC';
		}
		if($select == 60){
			$select_w = 'order by `money` ASC';
		}
	
		if($fen1){
			$count= $this->model->query("select * from `".C('DB_PREFIX')."shoplist` where `type` = 1 and `q_uid` is null and `shenyurenshu` != '0' and `isFree`=0 and `cateid` in ($sun_id_str) $select_w");
		}else{
			$count= $this->model->query("select * from `".C('DB_PREFIX')."shoplist` where `type` = 1 and `q_uid` is null and `shenyurenshu` != '0' and `isFree`=0 $select_w");
		}
		if($fen1){
			//$shoplist= $this->model->query("select * from `".C('DB_PREFIX')."shoplist` where `type` = 1 and `q_uid` is null and `cateid` in ($sun_id_str) $select_w limit $star,$end");
			$shoplist= $this->model->query("select * from `".C('DB_PREFIX')."shoplist` where `q_uid` is null and `shenyurenshu` != '0' and `isFree`=0 and `cateid` in ($sun_id_str) $select_w");
		}else{
			//$shoplist= $this->model->query("select * from `".C('DB_PREFIX')."shoplist` where `type` = 1 and `q_uid` is null $select_w limit $star,$end");
			$shoplist= $this->model->query("select * from `".C('DB_PREFIX')."shoplist` where `q_uid` is null and `shenyurenshu` != '0' and `isFree`=0 $select_w");
		}
		$max_renqi_qishu = 1;
		$max_renqi_qishu_id = 1;
	
		$this_time = time();
		if(count($shoplist) > 1){
			if($shoplist[0]['time'] > $this_time - 86400*3)
				$shoplist[0]['t_new_goods'] = 1;
		}
		$pagex=ceil(count($count)/$end);
		if($p<=$pagex){
			$shoplist[0]['page']=$p+1;
		}
		if($pagex>0){
			$shoplist[0]['sum']=$pagex;
		}else if($pagex==0){
			$shoplist[0]['sum']=$pagex;
		}
		
		$shoplist[0]['count'] = count($shoplist);
		$shoplist[0]['catename'] = $daohang;
		$this->ajaxReturn($shoplist);
	}
	
	//app首页底部版权
	private function copyright(){
		$this->ajaxReturn(array('html' => $this->__copyright()));
	}
	private function __copyright(){
		$web_copyright = M('Config')->where(array('name' => 'web_copyright'))->getField('value');
		$string = @stripslashes($web_copyright);
		return $string;
	}
	
	//index
	private function index(){
		$web_copyright = $this->__copyright();
		$renqi = $this->__renqiData();
		$homeget = $this->__homeget();
		$adver = $this->getSlides();
		$this->ajaxReturn(array(
			't' => 1,
			'web_copyright' => $web_copyright,
			'renqi' => $renqi,
			'homeget' => $homeget,
			'slides' => $adver
		));
	}
	
	private function __renqiData(){
		$shoplistrenqi = $this->model->query("select $this->field from `".C('DB_PREFIX')."shoplist` where `renqi`='1' and `q_end_time` is null and `isFree`=0 ORDER BY time DESC LIMIT 30");
		/*
		$max_renqi_qishu = 1;
		$max_renqi_qishu_id = 1;
		
		if(!empty($shoplistrenqi)){
			foreach ($shoplistrenqi as $renqikey =>$renqiinfo){
				if($renqiinfo['qishu'] >= $max_renqi_qishu){
					$max_renqi_qishu = $renqiinfo['qishu'];
					$max_renqi_qishu_id = $renqikey;
				}
			}
			$shoplistrenqi[$max_renqi_qishu_id]['t_max_qishu'] = 1;
		}*/
		$this_time = time();
		if(count($shoplistrenqi) > 0){
			//if($shoplistrenqi[0]['time'] > $this_time - 86400*3){
			//	$shoplistrenqi[0]['t_new_goods'] = 1;
			//}
			$data = array('status' => 1,'data' => $shoplistrenqi);
			//$this->ajaxReturn($data);
		}else{
			//$this->ajaxReturn(array('status' => 0));
			$data = array('status' => 0);
		}
		return $data;
	}
	
	//app首页人气商品
	private function renqi(){
		$data = $this->__renqiData();
		$slides = $this->getSlides();
		$data['slides'] = $slides;
		$this->ajaxReturn($data);
	}
	
	//购买记录
	private function userbuylist(){
		$this->getUserinfo('jsonp');
		$page = I('page',1,'intval');
		$member=$this->userinfo;
		$uid = $member['uid'];
// 		$total= $this->excq("select * from `@#_member_go_record` where `uid`='$uid' order by `id` DESC");
		$total = M('member_go_record')->where(array('uid' => $uid))->count();
		$getLimit = $this->getLimit($total,$page);
		$record = $this->excq("select id,code,code_tmp,username,uphoto,uid,shopid,shopname,shopqishu,gonumber,moneycount,huode,pay_type,ip,status,time from `@#_member_go_record` where `uid`='$uid' order by `id` DESC {$getLimit['limit']}",2);
		$model = M('shoplist');
		foreach ($record as $key => $value) {
			$record[$key]['thumb'] = $model->where(array('id' => $value['shopid']))->getField('thumb');
		}
		$this->ajaxReturn(array('status' => 1,'totalPage' => $getLimit['totalPage'],'data' => $record));
	}

	//购买记录详细
	private function userbuydetail(){
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		$crodid= intval($_GET['orderid']);
		if (!$crodid) $this->ajaxReturn(array('status' => 0,'msg' => '非法操作'));
		$record=$this->excq("select * from `@#_member_go_record` where `id`='$crodid' and `uid`='$member[uid]' LIMIT 1");
		if(!$record){
			$this->ajaxReturn(array('status' => 0,'msg' => '数据不存在'));
		}
		$lottery = get_shop_if_jiexiao($record['shopid']);
		$record['thumb'] = $lottery['thumb'];
		$record['goucode'] = yunma($record['goucode']);
		$record['time'] = microt($record['time']).'&nbsp;&nbsp;';
		$record['q_end_time'] = microt($lottery['q_end_time']);
		
		//倒计时差
		$diff_time = $lottery['q_end_time']-time();
		
		$this->ajaxReturn(array('status' => 1,'data' => $record,
				'lottery' => $lottery,
				'diffTime' => $diff_time,
				'webname' => getConfig('web_name_two')));
	}
	
// 	private function getLimit($total,$page=1,$pageSize=10){
// 		if (empty($pageSize)) $pageSize = 10;
// 		$totalPage = ceil($total/$pageSize);
// 		if ($page > 1){
// 			$start = $page;
// 			if ($totalPage <= $page){
// 				$start = $totalPage;
// 			}
// 		}else{
// 			$start = 1;
// 		}
// 		$limit = 'limit '.($start-1)*$pageSize.','.$pageSize;
// 		return array('limit' => $limit,'totalPage' => $totalPage);
// 	}
	
	//获得商品记录
	private function orderlist(){
		$page = I('page',1,'intval');
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		$total = M('member_go_record')->where("huode!=0 and uid=".$member['uid'])->count();
		$getLimit = $this->getLimit($total,$page);
		$orderlist['listItems']= $this->excq("select a.id as orderid,a.code,a.code_tmp,
				a.username,a.uphoto,a.uid,
				a.shopid,a.shopname,a.shopqishu,
				a.gonumber,a.moneycount,
				a.huode,a.pay_type,a.ip,
				a.status,a.time,b.* from `@#_member_go_record` a left join `@#_shoplist` b on a.shopid=b.id where b.q_uid='$member[uid]' and b.q_showtime='N' and a.huode!=0 order by a.time desc {$getLimit['limit']}",2);
		if(empty($orderlist['listItems'])){
			$this->ajaxReturn(array('status' => 0,'msg' => '暂无数据'));
		}else{
			foreach($orderlist['listItems'] as $key=>$val){
				unset($orderlist['listItems'][$key]['q_content']);
				unset($orderlist['listItems'][$key]['picarr']);
				unset($orderlist['listItems'][$key]['content']);
				$orderlist['listItems'][$key]['q_end_time']=microt($val['q_end_time']);
			}
			$orderlist['count']=$total;
			$orderlist['totalPage'] = $getLimit['totalPage'];
			$this->ajaxReturn(array('status' => 1,'data' => $orderlist));
		}
	}
	
	//app签到
	private function signdo(){
		# 签到时间限制（不能夸天哦。。）
		$time_start = '00:01';
		$time_stop= '23:59';
	
		# 每日签到增加福分
		$time_score = 100;
		$sign_award = M('sign_award')->order('id desc')->find();
		if (!empty($sign_award)){
			$time_score = $sign_award['count'];
		}
		# 连续签到的天数
		$time_day = 30;
		# 连续签到增加的福分
		$time_day_score = rand(10000,15000);
		
		function __userinfo($uid){
			$member = M('member')->where(array('uid' => $uid))->find();
			if (!$member['sign_in_date'] ) {
				$member['sign_in_date'] = '-';
			}else if ( $member['sign_in_date'] != date('Y-m-d') && $member['sign_in_date'] != date('Y-m-d',strtotime('-1 day')) ) {
				$member['sign_in_time'] = 0;
			}
			return $member;
		}
		
		if (isset($_REQUEST['submit']) || $_REQUEST['submit']=='submit' ) {
			$this->getUserinfo($this->jsonp);
			$uid = $this->uid;
			$member= M('member')->where(array('uid' => $uid))->find();
						
			if (!$member['mobile']) {
				$this->ajaxReturn(array('status' => 1,'msg' => '只有手机验证会员才能签到喔'));
	
			}else if ($member['sign_in_date'] == date('Y-m-d') ) {
					$this->ajaxReturn(array('status' => 1,'msg' => '您今天已经签到过了'));
	
			}else if ( strtotime(date('Y-m-d').$time_start ) > time() || strtotime(date('Y-m-d').$time_stop ) < time() ) {

			$this->ajaxReturn(array('status' => 1,'msg' => "现在不是签到时间！签到时间为{$time_start}点到{$time_stop}点"));
	
			} else {
				
			if ($member['sign_in_date'] == date('Y-m-d',strtotime('-1 day')) ){
				if ( $member['sign_in_time'] >= $time_day ) {
					$member['sign_in_time'] = 0;
				}
	
				$sign_in_time = $member['sign_in_time'] + 1;
				$sign_in_time_all = $member['sign_in_time_all'] + 1;
				$sign_in_date = date('Y-m-d');
						$score = $member['score'] + $time_score;
	
				if ( $sign_in_time >= $time_day ) {
				# 领取大礼包了
				$score += $time_day_score;
				$big = true;
				} else {
				$big = false;
				}
	
				$this->aud("INSERT INTO `".C('DB_PREFIX')."member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('".$member['uid']."', '1', '福分', '每日签到', '$time_score', '".time()."')");
				$this->aud("UPDATE `".C('DB_PREFIX')."member` SET score='".$score."',sign_in_time='".$sign_in_time."', sign_in_time_all='".$sign_in_time_all."', sign_in_date='".$sign_in_date."' where uid='".$member['uid']."'");
				if ( $big ) {
				$this->model->query("INSERT INTO `".C('DB_PREFIX')."member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('".$member['uid']."', '1', '福分', '签到大礼包', '$time_day_score', '".time()."')");
				
				$member = __userinfo($this->userinfo['uid']);
				$this->ajaxReturn(array('status' => 1,'userinfo' => $member,'msg' => "签到成功，成功领取{$time_score}福分。\r\n恭喜您获得{$time_day_score}福分的大礼包。\r\n您的当前福分为{$score}"));
				
				} else {
					$member = __userinfo($this->userinfo['uid']);
				$this->ajaxReturn(array('status' => 1,'userinfo' => $member,'msg' => "签到成功，成功领取{$time_score}福分。\r\n您的当前福分为{$score}。\r\n再连续签到".($time_day-$sign_in_time)."天就能领取大礼包啦，加油！！！"));
					
				}
				
			} else {
					
				$sign_in_time = 1;
				$sign_in_time_all = $member['sign_in_time_all'] + 1;
				$sign_in_date = date('Y-m-d');
				$score = $member['score'] + $time_score;
					$this->aud("INSERT INTO `".C('DB_PREFIX')."member_account` (`uid`, `type`, `pay`, `content`, `money`, `time`) VALUES ('".$member['uid']."', '1', '福分', '每日签到', '$time_score', '".time()."')");
					$this->aud("UPDATE `".C('DB_PREFIX')."member` SET score='".$score."',sign_in_time='".$sign_in_time."', sign_in_time_all='".$sign_in_time_all."', sign_in_date='".$sign_in_date."' where uid='".$member['uid']."'");
					$member = __userinfo($this->userinfo['uid']);
					$this->ajaxReturn(array('status' => 1,'userinfo' => $member,'msg' => "签到成功，成功领取{$time_score}福分。\r\n您的当前福分为{$score}"));
				}
				}
		}
	}
	
	//签到页面
	private function signto(){
		$this->getUserinfo('jsonp');
		$member = $this->userinfo;
		if (!$member['sign_in_date'] ) {
			$member['sign_in_date'] = '-';
		}else if ( $member['sign_in_date'] != date('Y-m-d') && $member['sign_in_date'] != date('Y-m-d',strtotime('-1 day')) ) {
			$member['sign_in_time'] = 0;
		}
		if($member['sign_in_date'] == date('Y-m-d')){
			$this->ajaxReturn(array('status' => 0,'userinfo' => $member,'msg' => '今天已经签到'));
		}else{
			$this->ajaxReturn(array('status' => 1,'userinfo' => $member,'msg' => '马上签到'));
		}
	}
	
	//佣金管理
	private function commissions(){
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		/*
		$memberdj=$this->db->GetList("select * from `@#_member_group`");
		$jingyan=$member['jingyan'];
		if(!empty($memberdj)){
			foreach($memberdj as $key=>$val){
				if($jingyan >= $val['jingyan_start'] && $jingyan<=$val['jingyan_end']){
					$member['yungoudj']=$val['name'];
				}
			}
		}
		*/
		$uid = $member['uid'];
		$recodetotal=0;   // 判断是否为空
		$shourutotal=0;
		$zhichutotal=0;
		$invifriends= $this->excq("select * from `@#_member` where `yaoqing`='$member[uid]' ORDER BY `time` DESC",2);
		//查询佣金表
		foreach ($invifriends as $key => $value) {
			$sqluid= $value['uid'];
			//查询邀请好友给我反馈的佣金
			$recodes[$sqluid]=$this->excq("select * from `@#_member_recodes` where `uid`='$sqluid' and `type`=1 ORDER BY `time` DESC",2);
			$user[$sqluid]['username']=	get_user_name($value);
		}
		//自己提现或充值
		$recodes[$uid]=$this->excq("select * from `@#_member_recodes` where `uid`='$uid' and `type`!=1 ORDER BY `time` DESC",2);
		$user[$uid]['username']= get_user_name($member);
		
		$recodearr='';
		$i=0;
		if(!empty($recodes)){
			foreach($recodes as $key=>$val){
				$username[$key] = $user[$key]['username'];
				foreach($val as $key2=>$val2){
					$recodearr[$i]=$val2;
					$i++;
				}
			}
		}
	
		$recodetotal=count($recodes);
		//查询   累计收入：元    累计(提现/充值)：元    佣金余额：元
		if(!empty($recodes)){
			foreach($recodes as $key=>$val){
				if($uid==$key){
					foreach($val as $key2=>$val2){
						$zhichutotal+=$val2['money'];	 //总佣金支出
					}
				}else{
					foreach($val as $key3=>$val3){
						$shourutotal+=$val3['money'];	 //总佣金收入
					}
				}
			}
		}
		$total=$shourutotal-$zhichutotal;  //计算佣金余额
		
		if(is_array($recodearr) && !empty($recodearr)){
			foreach ($recodearr as $key => $value) {
				$recodearr[$key]['uname'] = $username[$value['uid']];
				$recodearr[$key]['time'] = date('Y-m-d H:i:s',$value['time']);
				$recodearr[$key]['diff'] = $uid==$value['uid']?'-':'+ '.$value['money'];
				$recodearr[$key]['uimg'] = get_user_name($value['uid'],'img');
				if ($uid!=$value['uid']){
					$q_end_time = M('shoplist')->where(array('id' => $value['shopid']))->getField('q_end_time');
					if (empty($q_end_time)){
						$q_end_time = "openItem('item',{$value['shopid']},function(id){localData.set('goods_id',id);})";
					}else{
						$q_end_time = "openItem('dataserver',{$value['shopid']},function(id){localData.set('goods_id',id);})";
					}
					$recodearr[$key]['content'] = '<a href="javascript:'.$q_end_time.';" class="blue">'.$value['content'].'</a>';
				}
			}
		}
		
		$this->ajaxReturn(array(
			'status' => 1,
			'thumb' => $this->userinfo['thumb'],
			'score' => $this->userinfo['score'],
			'money' => $this->userinfo['money'],
			'username' => $this->userinfo['username'],
			'mobile' => $this->userinfo['mobile'],
			'shourutotal' => $shourutotal,
			'zhichutotal' => $zhichutotal,
			'utotal' => $total,
			'data' => $recodearr
		));
	}
	
	//提现
	private function cashout(){
		if(isset($_POST['submit1']) || isset($_POST['submit2'])){
			$this->getUserinfo();
		}else{
			$this->getUserinfo('jsonp');
		}
		$member=$this->userinfo;
		/*
		$memberdj=$this->db->GetList("select * from `@#_member_group`");
		$jingyan=$member['jingyan'];
		if(!empty($memberdj)){
			foreach($memberdj as $key=>$val){
				if($jingyan>=$val['jingyan_start'] && $jingyan<=$val['jingyan_end']){
					$member['yungoudj']=$val['name'];
				}
			}
		}
		*/
		$uid = $member['uid'];
		$total=0;
		$shourutotal=0;
		$zhichutotal=0;
		$cashoutdjtotal=0;
		$cashouthdtotal=0;
		//查询邀请好友id
		$invifriends=$this->excq("select * from `@#_member` where `yaoqing`='$member[uid]' ORDER BY `time` DESC",2);
	
		//查询佣金收入
		for($i=0;$i<count($invifriends);$i++){
			$sqluid=$invifriends[$i]['uid'];
			//查询邀请好友给我反馈的佣金
			$recodes[$sqluid]=$this->excq("select * from `@#_member_recodes` where `uid`='$sqluid' and `type`=1 ORDER BY `time` DESC",2);
		}
	
		//查询佣金消费(提现,充值)
		$zhichu=$this->excq("select * from `@#_member_recodes` where `uid`='$uid' and `type`!=1 ORDER BY `time` DESC",2);
	
		//查询被冻结金额
		$cashoutdj=$this->excq("select SUM(money) as summoney  from `@#_member_cashout` where `uid`='$uid' and `auditstatus`!='1' ORDER BY `time` DESC");
	
		if(!empty($recodes)){
			foreach($recodes as $key=>$val){
				foreach($val as $key2=>$val2){
					$shourutotal+=$val2['money'];	 //总佣金收入
				}
			}
		}
		if(!empty($zhichu)){
			foreach($zhichu as $key=>$val3){
				$zhichutotal+=$val3['money'];	//总支出的佣金
			}
		}

		$total=$shourutotal-$zhichutotal;  //计算佣金余额
		$cashoutdjtotal= $cashoutdj['summoney'];  //冻结佣金余额
		$cashouthdtotal= $total-$cashoutdj['summoney'];  //活动佣金余额
	
		if(isset($_POST['submit1'])){ //提现
			$money      = abs(intval($_POST['money']));
			$username   =htmlspecialchars($_POST['txtUserName']);
			$bankname   =htmlspecialchars($_POST['txtBankName']);
			$branch     =htmlspecialchars($_POST['txtSubBank']);
			$banknumber =htmlspecialchars($_POST['txtBankNo']);
			$linkphone  =htmlspecialchars($_POST['txtPhone']);
			$time  =time();
			$type  = -3;  //收取1/消费-1/充值-2/提现-3
	
			if($total<100){
				$this->ajaxReturn(array('status' => 0,'msg' => '佣金金额大于100元才能提现'),'json');
			}elseif($cashouthdtotal<$money){
				$this->ajaxReturn(array('status' => 0,'msg' => '输入额超出活动佣金金额'),'json');
			}elseif($total<$money ){
				$this->ajaxReturn(array('status' => 0,'msg' => '输入额超出总佣金金额'),'json');
			}else{
	
				//插入提现申请表  这里不用在佣金表中插入记录 等后台审核才插入
				$this->aud("INSERT INTO `@#_member_cashout`(`uid`,`money`,`username`,`bankname`,`branch`,`banknumber`,`linkphone`,`time`)VALUES
						('$uid','$money','$username','$bankname','$branch','$banknumber','$linkphone','$time')");
				$this->ajaxReturn(array('status' => 1,'msg' => '申请成功！请等待审核'),'json');
			}
		}
	
		if(isset($_POST['submit2'])){//充值
			$money      = abs(intval($_POST['txtCZMoney']));
			$type       = 1;
			$pay        ="账户";
			$time       =time();
			$content    ="使用佣金充值到购买账户";
			if($money <= 0 || $money > $total){
				$this->ajaxReturn(array('status' => 0,'msg' => '佣金金额输入不正确'),'json');
			}
			if($cashouthdtotal<$money){
				$this->ajaxReturn(array('status' => 0,'msg' => '输入额超出活动佣金金额'),'json');
			}
	
			//插入记录
			$account=$this->aud("INSERT INTO `@#_member_account`(`uid`,`type`,`pay`,`content`,`money`,`time`)VALUES
					('$uid','$type','$pay','$content','$money','$time')");
	
			// 查询是否有该记录
			if($account){
				//修改剩余金额
				$leavemoney=$member['money']+$money;
				$mrecode=$this->aud("UPDATE `@#_member` SET `money`='$leavemoney' WHERE `uid`='$uid' ");
				//在佣金表中插入记录
				$recode=$this->aud("INSERT INTO `@#_member_recodes`(`uid`,`type`,`content`,`money`,`time`)VALUES
						('$uid','-2','$content','$money','$time')");
	
				$this->ajaxReturn(array('status' => 1,'msg' => '充值成功'),'json');
			}else{
				$this->ajaxReturn(array('status' => 0,'msg' => '充值失败'),'json');
			}
		}
		$this->ajaxReturn(array(
				'status' => 1,
				'thumb' => $this->userinfo['thumb'],
				'score' => $this->userinfo['score'],
				'money' => $this->userinfo['money'],
				'username' => $this->userinfo['username'],
				'mobile' => $this->userinfo['mobile'],
				'shourutotal' => $shourutotal,
				'zhichutotal' => $zhichutotal,
				'utotal' => $total,
				'cashouthdtotal' => $cashouthdtotal,
				'cashoutdjtotal' => $cashoutdjtotal?$cashoutdjtotal:0
		));
		
	}
	
	//邀请管理
	private function invitation(){
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		$memberdj=$this->excq("select * from `@#_member_group`",2);
		$jingyan=$member['jingyan'];
		if(!empty($memberdj)){
			foreach($memberdj as $key=>$val){
				if($jingyan>=$val['jingyan_start'] && $jingyan<=$val['jingyan_end']){
					$member['yungoudj']=$val['name'];
				}
			}
		}
		$uid=$this->userinfo['uid'];
		$notinvolvednum=0;  //未参加购买的人数
		$involvednum=0;     //参加预购的人数
		$involvedtotal=0;   //邀请人数
		//查询邀请好友信息
		$invifriends=$this->excq("select * from `@#_member` where `yaoqing`='$member[uid]' ORDER BY `time` DESC",2);
		$involvedtotal=count($invifriends);
		
		for($i=0;$i<count($invifriends);$i++){
			$sqluid=$invifriends[$i]['uid'];
			$sqname=get_user_name($invifriends[$i]);
			$invifriends[$i]['sqlname'] = $sqname;
			$invifriends[$i]['uid2'] = idjia($sqluid);
			$invifriends[$i]['time'] = date('Y-m-d H:i:s',$invifriends[$i]['time']);
			//查询邀请好友的消费明细
			$accounts[$sqluid]=$this->excq("select * from `@#_member_account` where `uid`='$sqluid'  ORDER BY `time` DESC",2);
			//判断哪个好友有消费
			if(empty($accounts[$sqluid])){
				$notinvolvednum +=1;
				$invifriends[$i]['records'] = '未参与购买';
			}else{
				$involvednum +=1;
				$invifriends[$i]['records'] = '已参与购买';
			}
		}
		
		$uid = _encrypt($this->userinfo['uid']);
		$share_title = "注册组团云购 一元就能买IPONE 6S！一元就能得获得9D电影院！快去看看吧！";
		$share_desc = "全球唯一公开透明可自创团的云购平台！ 诚招全国地方独家运营商！ 4008121285";
		$share_link = WEB_PATH.'/mobile/user/register/'.$uid;
		if(!isset($share_title)){
			$share_title = getConfig('web_name');
		}
		if(!isset($share_desc)){
			$share_desc = getConfig('web_des');
		}
		if(!isset($share_link)){
			$share_link = getConfig('web_path');
		}
		if(!isset($share_img)){
			$share_img = getConfig('web_logo');
		}
		
		$this->ajaxReturn(array('status' => 1,
			'userinfo' => $this->userinfo,
			'involvedtotal' => $involvedtotal,
			'invifriends' => $invifriends,
			'share_title' => $share_title,
			'share_desc' => $share_desc,
			'share_link' => $share_link,
			'share_img' => $share_img,
			'involvednum' => $involvednum
		));
		
	}
	
	//提现记录
	private function cashoutrecord(){
		$this->getUserinfo('jsonp');
		$member=$this->userinfo;
		$uid = $member['uid'];
		
		if(isset($_GET['detail'])){
			$id = intval($_GET['id']);
			if (!$id){
				$this->ajaxReturn(array('status' => 0));
			}
			$data = M('member_cashout')->where(array('id' => $id,'uid' => $this->userinfo['uid']))->find();
			$_temp = array();
			foreach ($data as $key => $value) {
				switch ($key){
					case 'username':
						$_temp[] = "开户人：".$value;
						break;
					case 'bankname':
						$_temp[] = "开户银行：".$value;
						break;
					case 'branch':
						$_temp[] = "开户支行：".$value;
						break;
					case 'money':
						$_temp[] = "提现金额：".$value.'元';
						break;
					case 'banknumber':
						$_temp[] = "银行卡号：".$value;
						break;
					case 'linkphone':
						$_temp[] = "联系电话：".$value;
						break;
					case 'auditstatus':
						$status = $value==1 ?'已通过':'未审核';
						$_temp[] = "是否审核：".$status;
						break;
					case 'time':
						$_temp[] = "提现时间：".date('Y-m-d H:i:s',$value);
						break;
				}
			}
			$this->ajaxReturn(array('status' => 1,'data' => $_temp));
		}
		
		$recordarr=$this->excq("select * from  `@#_member_cashout`  where `uid`='$uid' ORDER BY `time` DESC limit 0,100",2);
		foreach ($recordarr as $key => $value){
			$recordarr[$key]['time'] = date('Y-m-d H:i:s',$value['time']);
		}
		$this->ajaxReturn(array('status' => 1,'list' => count($recordarr),'data' => $recordarr));
	}
	
	//分享配置
	private function shareconfig(){
		$uid = isset($_GET['uid'])?$_GET['uid']:'';
		$share_title = _htmtocode2(getConfig('wx_share_title'));
		$share_desc = _htmtocode2(getConfig('wx_share_desc'));
		$share_link = W_WEB_PATH.'/mobile/user/register/'.$uid;
		if(!isset($share_title)){
			$share_title = getConfig('web_name');
		}
		if(!isset($share_desc)){
			$share_desc = getConfig('web_des');
		}
		if(!isset($share_link)){
			$share_link = getConfig('web_path');
		}
		if(!isset($share_img)){
			$share_img = getConfig('web_logo');
		}
		$this->ajaxReturn(array('status' => 1,
				'share_title' => $share_title,
				'share_desc' => $share_desc,
				'share_link' => $share_link,
				'share_img' => G_WEB_PATH.'/'.$share_img
		));
	}
	
	
	/**
	 * 方法不存在
	 */
	private function error(){
		echo '方法不存在';
		$this->ajaxReturn(array('status' => 0,'msg' => '方法不存在'));
		exit;
	}
	
	//返回jsonp
	private function jsonp($result){
		$result = json_encode($result);
		echo $_GET['callback']."($result)";
	}
	
	/**
	 * Ajax方式返回数据到客户端
	 * @access protected
	 * @param mixed $data 要返回的数据
	 * @param String $type AJAX返回数据格式
	 * @return void
	 */
	private function ajaxReturn($data,$type='JSONP') {
		if(empty($type)) $type  =   C('DEFAULT_AJAX_RETURN');
		switch (strtoupper($type)){
			case 'JSON' :
				// 返回JSON数据格式到客户端 包含状态信息
				header('Content-Type:application/json; charset=utf-8');
				exit(json_encode($data));
			case 'XML'  :
				// 返回xml格式数据
				header('Content-Type:text/xml; charset=utf-8');
				exit(xml_encode($data));
			case 'JSONP':
				// 返回JSON数据格式到客户端 包含状态信息
				header('Content-Type:application/json; charset=utf-8');
				$handler  =   isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
				exit($handler.'('.json_encode($data).');');
			case 'EVAL' :
				// 返回可执行的js脚本
				header('Content-Type:text/html; charset=utf-8');
				exit($data);
			default     :
				// 用于扩展其他返回格式数据
				exit;
				break;
		}
	}
	
	/**
	 * 返回query执行sql的数据
	 * @param String $sql
	 * @param int $flag 1返回一条数据, 2返回多条数据或true/false, 3返回查询数据以id为数组key下标
	 * @return array/integer/mixed
	 */
	private function excq($sql,$flag=1,$ids=array(),$key='id'){
		if (empty($sql)) return false;
		if (strpos($sql, '@#_') !== false){
			$sql = str_replace('@#_', C('DB_PREFIX'), $sql);
		}
		$result = $this->model->query(trim($sql));
		if ($flag == 1){
			if (empty($result)) return false;
			$data = current($result);
			return $data;
		}elseif ($flag == 2){
			return $result;
		}elseif ($flag == 3){
			$_temp = array();
			foreach ($ids as $k => $v){
				foreach ($result as $index => $value){
					if ($v == $value[$key]){
						$_temp[$v] = $value;
					}
				}
			}
			return $_temp;
		}
	}
		
	/**
	 * 执行insert update delete的sql语句
	 * @param String $sql
	 * @return boolean|integer
	 */
	private function aud($sql){
		if (empty($sql)) return false;
		if (strpos($sql, '@#_') !== false){
			$sql = str_replace('@#_', C('DB_PREFIX'), $sql);
		}
		$type = strtoupper(mb_substr(trim($sql), 0,6));
		$state = $this->model->execute($sql);
		if ($state !== false){
			if ($type == 'INSERT'){
				$this->insert_id = $this->model->getLastInsID();
				return true;
			}elseif ($type == 'UPDATE' || $type == 'DELETE'){
				return $state;
			}
		}
		return false;
	}
	
	/**
	 * 普通购物
	*type  1 邮件
	*type  2 手机
	*type  3 邮件,手机
	*/
	private function send_shop_code(){
		if(!isset($_POST['send']) && !isset($_POST['uid']) && !isset($_POST['gid'])){
			exit(0);
		}
		$uid = abs($_POST['uid']);
		$gid = abs($_POST['gid']);	
		$sendinfo = $this->excq("SELECT id,send_type FROM `@#_send` WHERE `gid` = '$gid' and `uid` = '$uid'");
		if($sendinfo)exit(0);
		$member = $this->excq("SELECT * FROM `@#_member` WHERE `uid` = '$uid'");
		if(!$member)exit(0);
		$info = $this->excq("SELECT id,q_user_code,q_end_time,title,q_user FROM `@#_shoplist` WHERE `id` = '$gid' and `q_uid` = '$uid'");
		if(!$info)exit(0);
		$username = get_user_name($member,'username','all');
		$this->send_insert($uid,$gid,$username,$info['title'],'-1');
		$type = include_once APP_CORE.'/config/send.inc.php';
		if(empty($type))exit(0);
		$type = $type['type'];
		
		$q_time = abs(substr($info['q_end_time'],0,10));
	
		while(time() < $q_time){
			sleep(5);
		}
	
		$ret_send = false;
	
		if($type=='1'){
			if(!empty($member['email'])){
				send_email_code($member['email'],$username,$uid,$info['q_user_code'],$info['title']);
				$ret_send = true;
			}
		}
		if($type=='2'){
			if(!empty($member['mobile'])){
				send_mobile_shop_code($member['mobile'],$uid,$info['q_user_code']);
				$ret_send = true;
			}
	
		}
	
		if($type=='3'){
			if(!empty($member['email'])){
				send_email_code($member['email'],$username,$uid,$info['q_user_code'],$info['title']);
				$ret_send = true;
			}
			if(!empty($member['mobile'])){
				send_mobile_shop_code($member['mobile'],$uid,$info['q_user_code']);
				$ret_send = true;
			}
		}
		
		if($ret_send){
			$this->send_insert($uid,$gid,$username,$info['title'],$type);
		}
		exit(0);
	}

	/**
	  组团
	 @type  1 邮件
	@type  2 手机
	@type  3 邮件,手机
	*/
	public function t_send_shop_code(){
		if(!isset($_POST['send']) && !isset($_POST['uid']) && !isset($_POST['gid'])){
			exit(0);
		}
		$uid = abs($_POST['uid']);
		$gid = abs($_POST['gid']);
		$sendinfo = $this->excq("SELECT id,send_type FROM `@#_send` WHERE `gid` = '$gid' and `uid` = '$uid'");
		if($sendinfo)exit(0);
		$member = $this->excq("SELECT * FROM `@#_member` WHERE `uid` = '$uid'");
		if(!$member)exit(0);
		$info = $this->excq("SELECT id,q_user_code,q_end_time,title,q_user FROM `@#_teamgoods` WHERE `id` = '$gid' and `q_uid` = '$uid'");
		if(!$info)exit(0);
		$username = get_user_name($member,'username','all');
		$this->send_insert($uid,$gid,$username,$info['title'],'-1');
		$type = include_once APP_CORE.'/config/send.inc.php';		
		if(!$type)exit(0);
		$type = $type['type'];
		$q_time = abs(substr($info['q_end_time'],0,10));
		while(time() < $q_time){
			sleep(5);
		}
		//file_put_contents('team_send.txt', $member['email'].$info['q_user_code'].$info['title']);
		$ret_send = false;
		if($type=='1'){
			if(!empty($member['email'])){
				send_email_code($member['email'],$username,$uid,$info['q_user_code'],$info['title']);
				
				$ret_send = true;
			}
		}
		if($type=='2'){
			if(!empty($member['mobile'])){
				send_mobile_shop_code($member['mobile'],$uid,$info['q_user_code']);
				$ret_send = true;
			}
	
		}
		
		M('teamgoods')->where(array('id' => $gid))->setField('q_showtime','N');
	
		if($type=='3'){
			if(!empty($member['email'])){
				send_email_code($member['email'],$username,$uid,$info['q_user_code'],$info['title']);
				$ret_send = true;
			}
			if(!empty($member['mobile'])){
				send_mobile_shop_code($member['mobile'],$uid,$info['q_user_code']);
				$ret_send = true;
			}
		}
	
		if($ret_send){
			
			$this->send_insert($uid,$gid,$username,$info['title'],$type);
		}
		exit(0);
	}
	
	private function send_insert($uid,$gid,$username,$shoptitle,$send_type){
		$time=time();
		if($send_type == '-1'){
			$sql = "INSERT INTO `@#_send` (`uid`,`gid`,`username`,`shoptitle`,`send_type`,`send_time`) VALUES ";
			$sql.= "('$uid','$gid','$username','$shoptitle','$send_type','$time')";
			$this->aud($sql);
		}else{
			$this->aud("UPDATE `@#_send` SET `send_type` = '$send_type' WHERE `gid` = '$gid' and `uid` = '$uid'");
		}
	}
	
	/**
	 * https请求（支持GET和POST）
	 * @param $url
	 * @param string $data
	 * @return mixed
	 */
	private function https_request($url, $data = null){
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		//如果$data不是空使用POST
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
}